Replacing for loops with vectorization
Afficher commentaires plus anciens
Questions similar to this have been asked before, but I've struggled to understand the answers. I am looking to speed up my Matlab programs by avoiding for loops. I have seen the remark that Matlab is a high level programming language and so things like for loops shouldn't be necessary, but if anyone could help me figure out how to avoid them in my simple example I would very much appreciate it.
The following script simulates the motion of a pendulum quite well:
length=0.1;
g=9.81;
omega(1)=0;
theta(1)=2;
t(1)=0;
timeStep = 0.01;
t = t(1):timeStep:t(1)+(timeStep*9999);
for i=2:10000
omega(i) = omega(i-1) + (g/length)*sin(theta(i-1))*timeStep;
theta(i) = theta(i-1)+omega(i)*timeStep;
end
plot(t,theta);
xlabel('Time (s)');
ylabel('Theta (rad)');
I have figured out how to vectorize t, shown before the start of the for loop. The issue is that omega and theta are both part of two simultaneous equations, where the next value of theta needs to be calculated based on the previous value of omega, and the next value of omega needs to be calculated based on the previous value of theta.
Is it possible to do this to use vectorization instead of a for loop?
Thank you,
Kyle
P.S. This is for teaching, my students will appreciate anything that speeds up their work!
5 commentaires
KALYAN ACHARJYA
le 19 Fév 2021
Modifié(e) : KALYAN ACHARJYA
le 19 Fév 2021
"P.S. This is for teaching, my students will appreciate anything that speeds up their work!"
Slightly higher speed by considering preallocation of the arrays. Suggested avoid the "length" as a variable name, as MATLAB have it's own inbuilt function named as "length"
len=0.1;
g=9.81;
timeStep = 0.01;
t =0:timeStep:timeStep*9999;
omega=zeros(1,length(t));
theta=[2,zeros(1,length(t)-1)];
for i=2:length(t)
omega(i) = omega(i-1) + (g/len)*sin(theta(i-1))*timeStep;
theta(i) = theta(i-1)+omega(i)*timeStep;
end
plot(t,theta);
xlabel('Time (s)');
ylabel('Theta (rad)');
Time in my system
Elapsed time is 0.144906 seconds.
Kyle Baldwin
le 19 Fév 2021
"I am looking to speed up my Matlab programs by avoiding for loops. I have seen the remark that Matlab is a high level programming language and so things like for loops shouldn't be necessary"
Sometimes loops are necessary.
Sometimes loops are faster.
Sometimes vectorized code is faster.
It depends on many factors which cannot be summarized into one little nugget of advice like that.
KALYAN ACHARJYA
le 19 Fév 2021
Modifié(e) : KALYAN ACHARJYA
le 19 Fév 2021
@Stephen Cobeldick Finally I have confirmed in this case. Sir, thanks for your valuable advices.
Kyle Baldwin
le 19 Fév 2021
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Programming dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!