Simulating pendulum with a for loop

I was asked to simulate a pendulum with a for loop. However, I was struggling with the hold on and off command, and the animation I generated only consists of the x and y points, but the line that connects to moving x and y points remains at the original position. Any help or explanation will be appreicated.
Below is my code so far
L = 2;
g = 9.81;
squarerootvalue_gl = sqrt(g./L);
squarerootvalue_lg = sqrt(L./g);
T = 2 .* pi .* squarerootvalue_lg;
t = 0:0.01:T;
theta = pi./3 .* cos(squarerootvalue_gl*t);
x = L .* sin(theta);
y = L .* (1 - cos(theta));
A = [0 x];
B = [L y];
figure
line(A,B)
hold on
axis equal
for i = 1:length(t)
plot (A(i),B(i),'b.', 'MarkerSize', 10)
drawnow
end

Antworten (1)

Voss
Voss am 26 Aug. 2022

0 Stimmen

Notice that in each iteration of your loop you plot one point: (A(i),B(i)). That's why only the end of the pendulum shows up. If you want to show the entire pendulum moving, you have to plot two points - the other one being the fixed point at the top of the pendulum, (0,L), which is also (A(1),B(1)).
L = 2;
g = 9.81;
squarerootvalue_gl = sqrt(g./L);
squarerootvalue_lg = sqrt(L./g);
T = 2 .* pi .* squarerootvalue_lg;
t = 0:0.01:T;
theta = pi./3 .* cos(squarerootvalue_gl*t);
x = L .* sin(theta);
y = L .* (1 - cos(theta));
A = [0 x];
B = [L y];
figure
temp = [min(A) max(A)];
axis([temp 1+temp]);
p = line(NaN, NaN, 'Color','b', 'Marker','.', 'MarkerSize', 10);
for i = 2:length(t)
set(p,'XData',A([1 i]),'YData',B([1 i]));
drawnow
end

4 Kommentare

Laidog
Laidog am 26 Aug. 2022
I tried yours and the animation stopped midway. I need to do one full swing. I am just wondering how should I change your code so that it does one full swing? (from where it was, swings all the way to the left and back to where it was)
Voss
Voss am 26 Aug. 2022
When I run it, it does swing once all the way to the left and and then once back.
Laidog
Laidog am 26 Aug. 2022
I don't know how to upload my animation here, but when I run it, it lasted less than 1 second, and it didn't even swing past the origin. I am just confused what's wrong.
Voss
Voss am 26 Aug. 2022
Post your code as it is now.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Programming finden Sie in Hilfe-Center und File Exchange

Produkte

Gefragt:

am 26 Aug. 2022

Kommentiert:

am 26 Aug. 2022

Community Treasure Hunt

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

Start Hunting!

Translated by