Subplot for individual for loop angle
1 view (last 30 days)
Show older comments
Jun Hong Wang
on 17 Nov 2021
Commented: Jun Hong Wang
on 24 Nov 2021
I am trying to do subplot for each angle like the one below. But when I try to do it it only show the sine wave for all the angle on subplot(2,2,1).
Below is my code
for angle = [0.2 , deg2rad(7.5), deg2rad(30), deg2rad(45)]
for i=1
subplot(2,2,i)
%theta(0) = 0.2 rad
initial_x = [angle;0];
[t,x] = ode45(@fun, t, initial_x);
%figure
hold on
%graph for 0.2 rad of Part A (Non-Linear), plotted in red
plot(t,x(:,2))
%theta(0) = 0.2 rad
initial_y1 = [angle;0];
[t,y] = ode45(@fun1, t, initial_y1);
%graph for 0.2 rad of Part B (Linear), plotted in blue
plot(t,y(:,2))
grid on
title("Angular Velocity VS Time (" +angle+ " rad)")
xlabel('Time (s)')
ylabel('Angular Velocity (\omega)')
legend('Part A (Non-Linear)','Part B (Linear)')
hold off
end
end
2 Comments
Star Strider
on 17 Nov 2021
The plots appear to me to be correct.
What is the exact problem? (Also, if solving it requires ‘fun’ and ‘fun1’ they need to be posted.)
.
Accepted Answer
Drishan Poovaya
on 24 Nov 2021
Hi,
the reason the graph isn't being plotted the way you expect is because your nested for loop structure is incorrect for this case. You want 4 plots on different subplots. Refer to the code below. It is identical to your code but I've modified the for loops. Only one for loop is required for plotting, and a variable i is used to select the different subplots
close all
clear
%Graph for velocity against time
%0.1 rad, 0.13 rad, 0.52 rad, 0.79 rad are plotted together
global g l
g = 9.81; %gravity
l = 9.81; %length
dt = 0.001; %time interval
t = 0:dt:10; %time from 0 to 10
%start at subplot 2,2,1
i = 1;
for angle = [0.2 , deg2rad(7.5), deg2rad(30), deg2rad(45)]
subplot(2,2,i);
% increment i, so next plot is on next subplot and so on
i = i+1;
%theta(0) = 0.2 rad
initial_x = [angle;0];
[t,x] = ode45(@fun, t, initial_x);
%figure
hold on
%graph for 0.2 rad of Part A (Non-Linear), plotted in red
plot(t,x(:,2))
%theta(0) = 0.2 rad
initial_y1 = [angle;0];
[t,y] = ode45(@fun1, t, initial_y1);
%graph for 0.2 rad of Part B (Linear), plotted in blue
plot(t,y(:,2))
grid on
title(sprintf('Angular Velocity VS Time (%.2f rad)', angle));
xlabel('Time (s)')
ylabel('Angular Velocity (\omega)')
legend('Part A (Non-Linear)','Part B (Linear)')
hold off
end
function dxdt = fun(~,x) %Non-linear function (Part A)
global g l
dx1dt = x(2);
dx2dt = -(g/l)*sin(x(1));
dxdt = [dx1dt;dx2dt];
end
function dydt = fun1(~,y) %Linear function (Part B)
global g l
dy1dt = y(2);
dy2dt = -(g/l)*(y(1));
dydt = [dy1dt;dy2dt];
end
More Answers (0)
See Also
Categories
Find more on Particle & Nuclear Physics in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!