Sum specific rows of an array
12 次查看(过去 30 天)
显示 更早的评论
Hi,
I have an array like:
0.2 2 3
1 3 4
1 4 6
0.8 4 6
2 5 1
1 6 2
0.4 6 2
Now I want to code that MATLAB sums up the values of the 1st column in the rows where the value of the 2nd and 3rd column match.
So the result should look like this below:
0.2 2 3
1 3 4
1.8 4 6
2 5 1
1.4 6 2
I hope someone can help me, thank you!
3 个评论
采纳的回答
Andrei Bobrov
2019-1-23
A = [0.2 2 3
1 3 4
1 4 6
0.8 4 6
2 5 1
1 6 2
0.4 6 2];
[a,~,c] = unique(A(:,2:3),'rows','stable');
out = [accumarray(c,A(:,1)),a];
更多回答(1 个)
s
2019-1-23
clc;
clear all;
A = [0.2 2 3;1 3 4;1 4 6;0.8 4 6;2 5 1;1 6 2;0.4 6 2];
B = size (A,1);
Result = [];
n = 0;
for i = 1:1:B-1
if (A(i,2) == A(i+1,2) && A(i,3) == A(i+1,3))
n = n+1;
end
end
for j = 1:1:B-n
if (A(j,2) == A(j+1,2) && A(j,3) == A(j+1,3))
Sum = A(j,1)+A(j+1,1);
Result = [Result; Sum A(j,2) A(j,3)]
A([j+1],:) = [];
else
Result = [Result; A(j,1) A(j,2) A(j,3)]
end
end
This should help
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!