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

1 Ansicht (letzte 30 Tage)
Mehdi
Mehdi am 8 Mär. 2015
Kommentiert: Mehdi am 13 Mär. 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.

Antworten (1)

Jan
Jan am 8 Mär. 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 Kommentare
Stephen23
Stephen23 am 11 Mär. 2015
Why not just vectorize the whole thing? There don't seem to be any slow operations involved, so it is the nested loops that are slowing this down, hence remove the loops.
Mehdi
Mehdi am 13 Mär. 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?

Melden Sie sich an, um zu kommentieren.

Tags

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by