cumulative sum of some columns of matrix

3 次查看(过去 30 天)
I have a 100 x 12 matrix of monthly climate data values.
I want to create a matrix with the cumulative sum of the three previous months.
How can I use cumsum() to get the cumulative sum by row of a certain number of specified columns, not the whole row?

采纳的回答

KL
KL 2017-11-1
编辑:KL 2017-11-1
You seem to want to do cumsum along the second dimension, so trivial is to use
res = cumsum(yourMat,2);
but this will produce the typical cumsum. If you want to add every 3 columns only for a specific row,
yourRow = someval; %within your dimension range
cs = 1:size(yourMat,2);
cs1 = [1 1 cs(1:end-2)];
res = arrayfun(@(x,y) sum(yourMat(yourRow,x:-1:y)), cs, cs1, 'uni',0);
  3 个评论
KL
KL 2017-11-1
编辑:KL 2017-11-1
Ah yeah, I made some changes to my answer. Note that, it's only for a specific row (yourRow). For all the rows, from the top of my head, I'd superimpose it with another arrayfun. It doesn't look very elegant but still works for you.
res = arrayfun(@(z) arrayfun(@(x,y) sum(yourMat(z,x:-1:y)), cs, cs1, 'uni',0),1:yourRow,'uni',0)
Roisin Loughnane
Roisin Loughnane 2017-11-1
编辑:Roisin Loughnane 2017-11-1
It worked, thank you very much!
I used your code to loop over each row:
sst = table2array(sst(:,6:end));
res = zeros(size(sst));
for i = 1:length(sst)
cs = 1:size(sst,2);
cs1 = [1 1 cs(1:end-2)]; % 1 1 : 10
res(i,:) = arrayfun(@(x,y) sum(sst(i,x:-1:y)), cs, cs1);
end

请先登录,再进行评论。

更多回答(1 个)

Birdman
Birdman 2017-11-1
编辑:Birdman 2017-11-1
A=randi([1 10],100,12)
A(:,2:5)=(cumsum(A(1:100,2:5)')')
This two lines does the trick.

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by