Info

# Help needed to vectorize this code

1 view (last 30 days)
Mehdi on 18 Mar 2015
Closed: MATLAB Answer Bot on 20 Aug 2021
Hi everyone, I'm posting this for the second time so hopefully someone can help me with vectorizing my code. I have 3 for loops inside each other as seen here:
for A=1:a
for B=1:b
for C=1:c
do_something (A,B,C)
end
end
end
Here is the actual code:
mpd_new = 8000;
mpr1 = 40000;
aicon = 0.2;
mstr1 = 12000;
g0 = 9.81;
Irp1 = 317;
dt = 0.1;
for mssf1 = 1370:1400;
for t_i = 2:0.1:5;
for alp_max = 1:0.1:4;
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
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
end
end
end
The problem is that it is extremely slow. I tried to vectorize it as seen below but it's not working properly:
mpd_new = 8000;
mpr1 = 40000;
aicon = 0.2;
mstr1 = 12000;
g0 = 9.81;
Irp1 = 317;
dt = 0.1;
mssf1 = 1370:1400;
t_i = 2:0.1:5;
alp_max = 1:0.1:4;
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