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.

 채택된 답변

Arthur Roué
Arthur Roué 2020년 7월 17일
편집: Arthur Roué 2020년 7월 17일

0 개 추천

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

Ara Jo
Ara Jo 2020년 7월 17일
Thank you very much -- it works well!
Ara Jo
Ara Jo 2020년 7월 18일
A related question is.. how would you do it if you had a matrix rather than a column vector? For instance, if I have a 6 by 3 matrix X
X =
1 4 7
2 5 8
3 6 9
1 4 7
2 5 8
3 6 9
How could I turn this into 3 by 3 by suming up every two elements in each column and get:
Y=
3 9 15
4 10 16
5 11 17
I tried to use reshape again and it seems the matrix is sliced in an inconvinient way.. Thank you very much for your time!
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);
Ara Jo
Ara Jo 2020년 7월 18일
Works perfectly - thank you very much!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Alan Stevens
Alan Stevens 2020년 7월 17일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 Performance and Memory에 대해 자세히 알아보기

질문:

2020년 7월 17일

댓글:

2020년 7월 18일

Community Treasure Hunt

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

Start Hunting!

Translated by