How to collapse within a column vector
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Ara Jo
el 17 de Jul. de 2020
Comentada: Ara Jo
el 18 de Jul. de 2020
Hello,
I am trying to collapse a long column to a shorter one by suming across elements. For instance, if I have:
x =
1
2
3
4
5
6
7
8
9
I would like to sum up every three elements and arrive at:
y= 6
15
24
This is basically the 'collapse' function in Stata but I'm struggling to do it in Matlab. Thanks for your advide.
0 comentarios
Respuesta aceptada
Arthur Roué
el 17 de Jul. de 2020
Editada: Arthur Roué
el 17 de Jul. de 2020
You can use the sum function after reshape your vector into a matrix
vX = 1:9;
Interval = 3;
mX = reshape(vX, Interval, numel(vX)/Interval)
mX =
1 4 7
2 5 8
3 6 9
sum(mX)
ans =
6 15 24
/!\ reshape() won't work if the number of elements in vX is not a multiple of Interval
4 comentarios
Alan Stevens
el 18 de Jul. de 2020
How about:
X = [1 4 7; 2 5 8; 3 6 9; 1 4 7; 2 5 8; 3 6 9];
X = X(:);
X = reshape(X,2,length(X)/2);
Y = sum(X);
Y = reshape(Y, 3, length(Y)/3);
Más respuestas (1)
Alan Stevens
el 17 de Jul. de 2020
One possibility is:
x = 1:12;
for i = 1:length(x)/3
p = 3*(i-1)+1;
y(i) = sum(x(p:p+2));
end
Ver también
Categorías
Más información sobre Sparse Matrices 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!