sum of row in pattern

1 view (last 30 days)
ANAND ASP
ANAND ASP on 28 Nov 2020
Edited: Adam Danz on 28 Nov 2020
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

Answers (4)

David Hill
David Hill on 28 Nov 2020
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

Image Analyst
Image Analyst on 28 Nov 2020
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

Stephen23
Stephen23 on 28 Nov 2020
Edited: Stephen23 on 28 Nov 2020
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];
[U,~,X] = unique(Data(:,1:2));
Y = [Data(:,3);Data(:,3)];
Z = [U,accumarray(X,Y)]
Z = 9×2
1.0000 0 2.0000 0 3.0000 0 4.0000 0.3340 5.0000 0.4820 6.0000 0.5160 7.0000 0.4550 8.0000 0.3580 9.0000 0.5670

Adam Danz
Adam Danz on 28 Nov 2020
Edited: Adam Danz on 28 Nov 2020
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))]
out = 9×2
1.0000 0 2.0000 0 3.0000 0 4.0000 0.3340 5.0000 0.4820 6.0000 0.5160 7.0000 0.4550 8.0000 0.3580 9.0000 0.5670
Slowest (1-line challenge)
out = [unique(Data(:,1:2)), arrayfun(@(i)sum(Data(any(Data(:,1:2)==i,2),3)), unique(Data(:,1:2)))]
out = 9×2
1.0000 0 2.0000 0 3.0000 0 4.0000 0.3340 5.0000 0.4820 6.0000 0.5160 7.0000 0.4550 8.0000 0.3580 9.0000 0.5670
Comparison of 10,000 iterations between existing solutions.

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!