Borrar filtros
Borrar filtros

Sum specific rows of an array

10 visualizaciones (últimos 30 días)
yinki23
yinki23 el 23 de En. de 2019
Respondida: s el 23 de En. de 2019
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 comentarios
yinki23
yinki23 el 23 de En. de 2019
Sorry if I was unspecific.
For example, rows no.3 and no.4 both have 4 and 6 in columns no.2 and no.3. So I want to sum these 2 rows up in column 1 (1+0.8). Same with rows no.6 and no.7.
I hope this helps you understand my question.
James Tursa
James Tursa el 23 de En. de 2019
Are the values in columns 2 and 3 always positive integers?

Iniciar sesión para comentar.

Respuesta aceptada

Andrei Bobrov
Andrei Bobrov el 23 de En. de 2019
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 comentario
yinki23
yinki23 el 23 de En. de 2019
Thank you so much! Works perfect for me!

Iniciar sesión para comentar.

Más respuestas (1)

s
s el 23 de En. de 2019
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

Categorías

Más información sobre Matrix Indexing en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by