Improve speed of indexing

4 views (last 30 days)
Elric
Elric on 14 Mar 2016
Edited: Ced on 14 Mar 2016
Hello,
I am trying to do a simple Monte Carlo simulation in a mean reverting AR(lags) model using the following code
for j = 1:nPaths
for i = lags+1:nPeriods+1
F(i,j) = Season(i) + ar*(Y(i-lags:i-1)-Season(i-lags:i-1)) + sqrt(S2(i-lags)).*R(i-lags,j);
end
end
where lags is the number of lags of the AR(lags) model, Season is a seasonality function, R are some random numbers, S2 is the variance and ar is the vector that contains the estimated parameters of the AR model (dimension [lags,1]).
By running the code I have noticed that it takes less than a second if lags = 1 but the time increases 20fold if lags is bigger number, e.g lags =3.
Using the profiler I found that the problem is in the indexing of Y and Season,
ar*(Y(i-lags:i-1)-Season(i-lags:i-1))
So, is there a way to improve this part? or the whole double loop.
Thank you in advance, Elric
  1 Comment
Ced
Ced on 14 Mar 2016
Edited: Ced on 14 Mar 2016
Do you preallocate F?
Things you could/should do in case you have not yet done it:
- preallocate F, i.e. F = zeros(nPeriods+1,nPaths);
- precompute the whole season vector (unless it is already one, but you said it's a function).
- You could precompute dYS = Y-Season. The operation in the loop would then be ar*dYS(i-lags:i-1). This is essentially computing the correlation. There are methods to increase the speed here, but I don't see why this operation would be so expensive.
- The last term can also be precomputed in vector form, i.e. repmat(sqrt(S2),1,nPaths).*R.
- Then: None of the operations in the for loop are recursive as far as I can tell. In other words, you might be able to get rid of the for loop completely (at least the inner one, the outer one would be tricky) at the cost that it may not be readable anymore.
Not a complete solution, sorry, but maybe this helps.
Cheers
PS: Could you give us the dimensions/orientation of your matrices/vectors? E.g. I think the variance is saved in a vector? row, or column? etc.
EDIT: added tipps

Sign in to comment.

Answers (0)

Categories

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!