Summing up subsequent rows if equal
Mostra commenti meno recenti
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 ];
Risposta accettata
Più risposte (3)
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
1 Commento
neil vaz
il 19 Lug 2023
Diya Tulshan
il 19 Lug 2023
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!
1 Commento
neil vaz
il 19 Lug 2023
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
1 Commento
neil vaz
il 19 Lug 2023
Categorie
Scopri di più su Matrix Indexing in Centro assistenza e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!