Reducing the running time of a for loop iterating through cells

1 view (last 30 days)
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
Jan
Jan on 14 Nov 2021
Edited: Jan on 14 Nov 2021
It would be very useful to provide some test data, e.g. created by some rand() calls. It is hard to optimize code without running it on a typical set of inputs.
Why do you use a cell array? As far as I understand a matrix would be more efficient.
Anna Mogilevskaja
Anna Mogilevskaja on 14 Nov 2021
This is how S is created:
%% 2) Getting the grid for K
K1 = 0.1;
Kn = 0.4;
space = (Kn - K1)/(nk-1);
gridk = NaN(1,nk-1);
for k = 1:100
gridk(k) = K1 + (k-1)*space;
end
%% 3) Getitng the grid for M
M1 = 0;
Mn = 0.5;
space = (Mn - M1)/(nm-1);
gridm = NaN(1,nm-1);
for m = 1:100
gridm(m) = M1 + (m-1)*space;
end
%% 4) Getting the list with all the possible states
S = {};
for k = 1:100
for m = 1:100
S{end+1} = {gridk(k), gridm(m)};
end
end

Sign in to comment.

Answers (1)

Jan
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

Categories

Find more on MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!