MATLAB Answers

Alternative method needed for a few 'for' loops inside each other

9 views (last 30 days)
Mehdi
Mehdi on 8 Mar 2015
Commented: Mehdi on 13 Mar 2015
Hi,
I have 4 for loops inside each other as seen here:
for A=1:a
for B=1:b
for C=1:c
for D=1:d
do_something (A,B,C,D)
end
end
end
end
The values of A, B, C, D are dependent on each other so I can't calculate them separately. The issue is that this is extremely slow. Could anyone please help me with an alternative fast method? Thank you very much for your time and help.

Answers (1)

Jan
Jan on 8 Mar 2015
No. It is impossible to give a useful suggestion based on this abstract code. The problem is not the nested loops, but the code hidden behind "do_something". The explanation "A, B, C, D are dependent" does not allow to understand the underlying concept.
The profiler helps to identify teh bottlenecks of the program. Use it and post the corresponding code in a less simplified manner. Then a helpful suggestion is possible.
  4 Comments
Mehdi
Mehdi on 13 Mar 2015
I did that as you see below:
mpd_new = 8000;
mpr1 = 40000;
aicon = 0.2;
mstr1 = 12000;
g0 = 9.81;
Irp1 = 317;
dt = 0.1;
mssf1 = 1370:1400; % No. of elements is 31.
t_i = 2:0.1:5; % No. of elements is 31.
alp_max = 1:0.1:4; % No. of elements is 31.
t1 = 0;
V1_X_cut = eps;
V1_Z_cut = 0;
ht1 = 0;
pcg1 = 90;
flp1 = 90;
alp1 = 0;
m_in1 = mstr1+mpr1+mpd_new;
m_f1 = m_in1-mpr1;
Mcrnt1 = m_in1-t1.*mssf1;
thst1 = mssf1.*Irp1.*g0;
while Mcrnt1 > m_f1
Expon1 = exp(aicon.*(t_i-t1));
alp1 = -4.*alp_max.*Expon1.*(1-Expon1);
flp1 = atan(V1_Z_cut./V1_X_cut).*180./pi;
pcg1 = flp1+alp1;
pchrd1 = pcg1.*pi./180;
acc_z1 = thst1.*sin(pchrd1)./Mcrnt1;
acc_x1 = thst1.*cos(pchrd1)./Mcrnt1;
V1_X_cut = V1_X_cut+acc_x1.*dt;
V1_Z_cut = V1_Z_cut+acc_z1.*dt;
V_cr1 = sqrt(V1_X_cut.^2 + V1_Z_cut.^2);
ht1 = ht1+V1_Z_cut.*dt;
Mcrnt1 = Mcrnt1-dt.*mssf1;
t1 = t1+dt;
end
V_cr1
But apparently, the while loop runs only once. Obviously it should run the while loop 31*31*31=29791 times for each element of each vector. Any idea how this should be implemented?

Sign in to comment.

Tags

Products

Community Treasure Hunt

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

Start Hunting!