问题
I have an cross-sectional array with columns as prices for each date. I want to create another array with a rolling sum for window of 30 days. I would prefer not to use a for loop. Currently, I am using the following code for one column:
for i=31:n
for j=i-30:i-1
x = x + y(j)
end
sum(i) = x
end
I need to this for all securities and thus the code will have to run multiple times for all elements in a dataset.
回答1:
Use a combination of cumsum
's!
data = 1:10;
n = length(data);
window = 3;
rollSum = cumsum(data)-[zeros(1,window), cumsum(data(1:n-window))];
rollSum =
1 3 6 9 12 15 18 21 24 27
1=1
1+2=3
1+2+3=6
2+3+4=9
3+4+5=12
回答2:
For each column x
, You can convolve with a sequence of 30 ones, and then remove the initial and final transients:
N = 30;
y = conv(x,ones(N,1));
y = y(N:end-N+1);
If X
is a matrix, you can similarly process all columns at the same time:
y = conv2(ones(N,1),1,X);
y = y(N:end-N+1,:);
回答3:
This can be very easy with filter
.
Suppose you have a simple vector of ones:
x = ones(100,1);
Then we just a apply a filter on it like so:
filter(ones(1,30),1,x)
This also works if x
is a matrix, for example ones(100,2)
.
回答4:
Starting Matlab 2016a there is command movsum
http://www.mathworks.com/help/matlab/ref/movsum.html
来源:https://stackoverflow.com/questions/18142720/rolling-sum-in-matlab