Reducing the running time of a for loop iterating through cells
1 view (last 30 days)
Show older comments
Hi,
I have a question concerning the reduction of the running time of a code. It is quite the complex formula but I will try to explain my issue as clear as possible.
I have the following formula:
And I have a 1x10000 cell S which contains 10000 1x2 cells. The cells are combinations of K and M. Now, I would like to iterate through S, picking K and M for two different periods. This is why I have two for loops. k for t and m for t+1.
In the code, M(t+1) is denoted as S{m}{2}, M is denoted as S{k}{2}, K(t+1) is denoted as S{m}{1} and K(t) as S{k}{1}.
The loops calculate c(t) first for the first row, going trough all columns. And then continues to the second row and so on and so on.
The code is the following:
for k = 1:10000
for m = 1:10000
C(k, m) = [(1 - a1*(1-(S{m}{2} - (1-phi)*S{k}{2})/(gamma*(S{k}{1}^alpha)))^a2)/(1+b1*(S{k}{2}^b2))] * (S{k}{1}^alpha) + (1-delta)*S{k}{1} - S{m}{1};
end
end
Gamma, a1, a2, b1, b2, alpha and delta are given parameters.
The code is running but needs a tremendous amount of time. Does anyone have an idea how I can reduce the running time.
Thanks for your help.
Greeting Anna
2 Comments
Answers (1)
Jan
on 14 Nov 2021
Is C pre-allocated?
Why do you use square brackets? This is the concatenation operator in Matlab. As far as I understand the used elements are scalars, so [] is a waste of time? If you provide some inputs, this would be clear immediately.
The power operation ^ is extremly expensive. Avoid to apply it repeatedly to the same values:
C = zeros(10000, 10000):
for k = 1:10000
c1 = (1 - phi) * S{k}{2};
c2 = S{k}{1}^alpha;
c3 = 1 + b1 * (S{k}{2}^b2);
c4 = (1 - delta) * S{k}{1};
for m = 1:10000
C(k, m) = ((1 - a1 * (1 - (S{m}{2} - c1) / ...
gamma * c2) ^ a2) / c3) * c2 + c4 - S{m}{1};
end
end
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!