sum of row in pattern
조회 수: 2 (최근 30일)
이전 댓글 표시
Data= [ 1 4 0.0000;
2 7 0.0000;
3 9 0.0000;
4 5 0.1760;
4 6 0.1580;
5 7 0.3060;
6 9 0.3580;
7 8 0.1490;
8 9 0.2090]
i expect answer like this, its nothing but the similar vaule in 1st and 2nd column according to that sum of 3rd column
ANS= 1 0.0000
2 0.0000
3 0.0000
4 0.3340
5 0.4820
6 0.5160
7 0.4550
8 0.3580
9 0.5670
ex.: take number 4 => 0.0000 + 0.1760 + 0.1580 = 0.3340
take number 7 => 0.0000 + 0.3060 + 0.1490 = 0.4550
댓글 수: 0
답변 (4개)
David Hill
2020년 11월 28일
k=unique(Data(:,1:2));
y=zeros(length(k),2);
for m=1:length(k)
y(m,:)=[k(m),sum(Data(logical(ismember(Data(:,1),k(m))+ismember(Data(:,2),k(m))),3))];
end
댓글 수: 0
Image Analyst
2020년 11월 28일
Try this:
Data = [ 1 4 0.0000;
2 7 0.0000;
3 9 0.0000;
4 5 0.1760;
4 6 0.1580;
5 7 0.3060;
6 9 0.3580;
7 8 0.1490;
8 9 0.2090]
col3 = Data(:, 3)
for row = 1 : max(max(Data(:, 1:2)))
rowsToUse = any(Data(:, 1:2) == row, 2)
theSums(row) = sum(col3(rowsToUse))
end
댓글 수: 0
Adam Danz
2020년 11월 28일
편집: Adam Danz
2020년 11월 28일
Data= [ 1 4 0.0000;
2 7 0.0000;
3 9 0.0000;
4 5 0.1760;
4 6 0.1580;
5 7 0.3060;
6 9 0.3580;
7 8 0.1490;
8 9 0.2090];
Fastest method (so far)
D = [Data(:,[1,3]);Data(:,[2,3])];
out = [unique(D(:,1)),accumarray(D(:,1),D(:,2))]
Slowest (1-line challenge)
out = [unique(Data(:,1:2)), arrayfun(@(i)sum(Data(any(Data(:,1:2)==i,2),3)), unique(Data(:,1:2)))]
Comparison of 10,000 iterations between existing solutions.
댓글 수: 0
참고 항목
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!