I would like to sum a 2 dim array group by value in second column
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
simon lumsdon
el 18 de Jun. de 2022
Comentada: Abolfazl Chaman Motlagh
el 18 de Jun. de 2022
I have an nX2 array
0.1 5
0.3 5
0.34 2
0.4 3
0.1 5
-.9 1
-6 2
and want to sum the first column grouped by the second to create an nX2 array that looks like
-0.9 1
-5.66 2
.4 3
0.5 5
I am sure its simple but its giving me brain ache :-)
Many thanks
0 comentarios
Respuestas (1)
Abolfazl Chaman Motlagh
el 18 de Jun. de 2022
there are a lot of ways to do this, here's a simple solution. i would recommend you to understand every line and run it line by line. try writing this code vectorize, i mean without for loop :)
X = [rand(6,1),randi(4,6,1)]
Y = unique(X(:,2));
Y(end,2)=0;
for i=1:size(X,1)
ind = X(i,2)==Y(:,1);
Y(ind,2) = Y(ind,2) + X(i,1);
end
Y = flip(Y,2)
2 comentarios
Abolfazl Chaman Motlagh
el 18 de Jun. de 2022
Here's a one line solution :)
X = [rand(6,1),randi(4,6,1)]
Y = [sum((X(:,2) == unique(X(:,2))') .* repmat(X(:,1),1,numel(unique(X(:,2)))))' , unique(X(:,2))]
Ver también
Categorías
Más información sobre Logical en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!