Summing up subsequent rows if equal
1 回表示 (過去 30 日間)
古いコメントを表示
well, I have been trying to sum up the values of the third column if the values of the rows (considering values in the first and second column only) tare equal. But couldnt suceed. It would be of great help if anyone would help me out with it.
A = [ 2 3 5
3 4 5
2 3 5
3 4 5
5 6 6
2 3 5
5 6 6
3 4 5 ];
The code i wrote is as follows
m,n] = size (A);
for i = 1:(m-1)
BB=[];
for j = i+1:(m)
if A(i,1)== A(j,1)
if A(i,2)== A(j,2)
B(i)= A(i, 3)+ A(j,3)
BB(k)=[A(i,1),A(i,2),BB(k)+B(i)]
end
end
end
end
The result I need is as follows
BB= [ 2 3 15
3 4 15
5 6 12 ];
0 件のコメント
採用された回答
Dyuman Joshi
2023 年 7 月 19 日
編集済み: Dyuman Joshi
2023 年 7 月 19 日
There is another approach you can follow -
A = [ 2 3 5
3 4 5
2 3 5
3 4 5
5 6 6
2 3 5
5 6 6
3 4 5];
%Get the unique combinations of rows from the first two columns
%and the rows they are in
[B,~,rowidx] = unique(A(:,1:2),'rows')
%Get the sum of values (i.e. 3rd column of A) corresponding to same indices
S = accumarray(rowidx,A(:,3))
%Final output
Out = [B S]
2 件のコメント
その他の回答 (3 件)
Angelo Yeo
2023 年 7 月 19 日
A = [2 3 5
3 4 5
2 3 5
3 4 5
5 6 6
2 3 5
5 6 6
3 4 5 ];
kindOfRowVec = unique(A(:, 1:2),'rows');
BB = [kindOfRowVec, zeros(size(kindOfRowVec, 1), 1)];
for i_kind = 1:size(kindOfRowVec, 1)
idx = any(A(:, 1:2) == kindOfRowVec(i_kind, :), 2);
BB(i_kind, 3) = sum(A(idx, 3));
end
BB
Diya Tulshan
2023 年 7 月 19 日
Hii Neil Vaz,
I understand you want to debug the code and get the desired output.
Here's a solution that might help:-
A = [2 3 5;
3 4 5;
2 3 5;
3 4 5;
5 6 6;
2 3 5;
5 6 6;
3 4 5];
% Extract the first two columns
first_two_cols = A(:, 1:2);
% Get unique combinations of the first two columns
unique_combinations = unique(first_two_cols, 'rows', 'stable');
% Initialize the sumvalues array
sumvalues = zeros(size(unique_combinations, 1), 1);
% Loop through each unique combination
for i = 1:size(unique_combinations, 1)
% Find the rows that match the current unique combination
matching_rows = all(first_two_cols == unique_combinations(i, :), 2);
% Sum the corresponding values from the third column
sumvalues(i) = sum(A(matching_rows, 3));
end
% Combine the unique combinations with the summed values
finalvalue= [unique_combinations, sumvalues];
You will be able to see the desired output in the workspace when you run the above code.
Kindly refer to the link below to get a good overview about the function that i have used:
Hope it helps!
Chunru
2023 年 7 月 19 日
A = [ 2 3 5
3 4 5
2 3 5
3 4 5
5 6 6
2 3 5
5 6 6
3 4 5 ];
[C, ia, ic] = unique(A(:, 1:2), 'rows');
D = [C zeros(size(C,1), 1)];
for i=1:size(C, 1)
D(i, 3) = sum(A(ic==i, 3));
end
D
参考
カテゴリ
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!