MATLAB Answers

Repeat a cumulative sum in a matrix

조회 수: 3(최근 30일)
Francis Chabot
Francis Chabot 2021년 8월 16일
댓글: Francis Chabot 2021년 8월 16일
Hello,
I have matrix of dimensions 2784x252 which represents monthly returns. I am trying to put them into annual returns which would return a matrix of 2784x21 (21 x 12 = 252). To do that I need to sum for each row, 12 column at a time. I've tried to use the function cumsum but it won't work because it returns an array with only one column which isn't what I need to do.
Since I need to repeat the sum of 12 column 21 times which is the number of years I have, I thought using a loop could help but I can't find a way that it woulld work.
Thanks for the help,
Best regards,
Frank

채택된 답변

Scott MacKenzie
Scott MacKenzie 2021년 8월 16일
편집: Scott MacKenzie 2021년 8월 16일
Here's a way to do this without a loop:
% test data (monthly returns for many investments for 252 months)
M = rand(2784,252);
% reorganize with one row per month
M = M';
% create monthly datetime vector for 21 years (adjust as needed)
d2 = 2020; % finishing year
d1 = d2 - 21; % going back 21 years
dt = datetime(d1,1,1):calmonths(1):datetime(d2-1,12,1);
% add datetime vector to data and organize in timetable
T = array2table(M);
T.Time = dt';
TT1 = table2timetable(T);
% compute yearly returns for investments (sum of monthly returns)
TT2 = retime(TT1, 'yearly', 'sum');
% plot yearly returns for 1st investment
plot(TT2.Time, TT2.M1);
xlabel('Year'); ylabel('Return');
  댓글 수: 3
Francis Chabot
Francis Chabot 2021년 8월 16일
Exactly what I needed!
Thanks

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

추가 답변(1개)

the cyclist
the cyclist 2021년 8월 16일
편집: the cyclist 2021년 8월 16일
% Made-up data
M = rand(2784,252);
% Reshape to put each year in a "slice" in the 3rd dimension
M2 = reshape(M,2784,12,[]);
% Show size of M2, just to illustrate
size(M2)
ans = 1×3
2784 12 21
% Get annual return by summing the monthly returns
% (That's not really accurate, though, right?
% Constant 1% monthly return will compound to greater than 12% annual return.)
A2 = sum(M2,2);
% Show size of A2, just to illustrate
size(A2)
ans = 1×3
2784 1 21
% Reshape again, to get back to a 2D array
A = reshape(A2,2784,[]);
% Show size again
size(A)
ans = 1×2
2784 21
  댓글 수: 1
Francis Chabot
Francis Chabot 2021년 8월 16일
Worked as well and is shorter which is even better!
Thank you

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

태그

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by