# How to call a function over a rolling window of data?

14 views (last 30 days)
Neha Verma on 13 Aug 2022
Commented: Neha Verma on 13 Aug 2022
I have a panel dataset with T=80 and N=23. I want to call a function over the rolling window of data with 20 periods in each window. Simply put, I want MATLAB to read my data as a numeric matrix (T*N). Pick the first 20 observations (T=1 to T=20), estimate the model and save the results. Then, pick up data over a rolling window (T=2 to T=21, T=3 to T=22... and so on), estimate the models and save results. So, the model will be estimated 64 times with 64 result matrices. How do I create the loop for this operation?
Thank you!

John D'Errico on 13 Aug 2022
Edited: John D'Errico on 13 Aug 2022
Yes, there are more sophisticated ways to do this. But for gods sake, why not just write a loop?
You don't say what size the result is. It could be scalar, or a matrix. regardless, just stuff it into something of the proper size.
result = zeros(1,64);
for t = 1:64
T = t + (0:19);
result(t) = fun(obs(T));
end
You don't need anything fancy here.
COULD you do it differently? Of course. For example, you COULD treate a matrix of indices. Somcething like
ind = (1:64)' + (0:19);
Now each row of that matrix is a rolling window of indices. But this is also wild overkill, if you will then loop over the rows of ind.
Neha Verma on 13 Aug 2022
Thank you, John! My result is in the form of a matrix. Wrote a loop as you suggested. It worked.