Borrar filtros
Borrar filtros

Summing Associated Values without Loop

1 visualización (últimos 30 días)
Jackson Jewett
Jackson Jewett el 29 de Nov. de 2022
Comentada: Jackson Jewett el 29 de Nov. de 2022
I have an nx2 matrix. Some elements in the first column repeat. I am interested in the elements in the second column that correspond to respective unique values in the first column. For each given unique value in the first column, I would like to sum each of the corresponding values in the second column. Ultimately, I would like to generate a new matrix in which every unique element in the first column is represented once, with the sum of its corresponding elements in the second column. The matrices I am using are huge, so I would like to do this without loops, but I cannot find a method to do so. Does anyone have any advice? Thank you!!
As an example, if given A, I would like to produce A' without using a loop:
A = [ 1 2
5 7
1 -1
3 5
5 2
1 7]
A'= [1 8
5 9
3 5]

Respuesta aceptada

Stephen23
Stephen23 el 29 de Nov. de 2022
Editada: Stephen23 el 29 de Nov. de 2022
A = [1,2;5,7;1,-1;3,5;5,2;1,7]
A = 6×2
1 2 5 7 1 -1 3 5 5 2 1 7
[U,~,X] = unique(A(:,1),'stable');
V = accumarray(X,A(:,2));
M = [U,V]
M = 3×2
1 8 5 9 3 5
Or another approach:
V = groupsummary(A(:,2),X,@sum);
M = [U,V]
M = 3×2
1 8 5 9 3 5

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Productos


Versión

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by