Repeat a cumulative sum in a matrix

7 次查看(过去 30 天)
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 个评论
Scott MacKenzie
Scott MacKenzie 2021-8-16
编辑:Scott MacKenzie 2021-8-16
I guess this could be coded-up without using a timetable, but you'd end up with the same data, so I'm not sure what sort of operations you are contemplating that can't be done. If you want the yearly data in matrix form, then you can do that from the timetable in my answer:
T2 = timetable2table(TT2);
M2 = table2array(TT2); % yearly data in matrix

请先登录,再进行评论。

更多回答(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

类别

Help CenterFile Exchange 中查找有关 Data Type Identification 的更多信息

标签

产品


版本

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by