Plotting 2 graphs, in the same window (not using subplot)

39 views (last 30 days)
Alexis
Alexis on 15 Feb 2026 at 0:33
Commented: Star Strider on 15 Feb 2026 at 11:40
I have read several questions/answers regarding plotting more than one graph in the same window using subplot. However, our instructor explicitly advised that we are not to use subplot.
Here is my code. I'm using an .m function file that I am calling from Live Editor. Only the second graph is displayed; the first graph won't display at all.
function LAB04ex1
t0=0; tf=50; y0=[-1;0];
[t,Y]=ode45(@f,[t0,tf],y0,[]);
y=Y(:,1);
v=Y(:,2);
figure(1);
plot(t,y,'b-+');
plot(t,v,'ro-');
xlabel('t'); ylabel('v(t)=y''t');
legend('y(t)','v(t)=y''(t)'); %add a legend
xlabel('t'); ylabel('y');
ylim([-4.8,4.8]); %adjust the y-limits for plot 1
grid on;
figure(2);
plot(y,v); axis square; xlabel('y'); ylabel('v');
xlim([-4,4]); ylim([-4.8,4.8]) %adust the y-limits for plot 2
grid on;
end
%------------------------------------------------------------
function dYdt = f(t,Y)
y=Y(1); v=Y(2);
dYdt = [v; 8*sin(t)-4*v-3*y];
end
Here are the instructions:
Any help, feedback or advice would be greatly appreciated. Thank you.

Answers (1)

Star Strider
Star Strider on 15 Feb 2026 at 1:08
If you are not supposed to use subplot, the only other option that comes quickly to mind is to use tiledlayout.
Your code would then become --
LAB04ex1
Warning: Ignoring extra legend entries.
function LAB04ex1
t0=0; tf=50; y0=[-1;0];
[t,Y]=ode45(@f,[t0,tf],y0,[]);
y=Y(:,1);
v=Y(:,2);
figure
tiledlayout(1,2)
nexttile
plot(t,y,'b-+');
plot(t,v,'ro-');
xlabel('t'); ylabel('v(t)=y''t');
legend('y(t)','v(t)=y''(t)'); %add a legend
xlabel('t'); ylabel('y');
ylim([-4.8,4.8]); %adjust the y-limits for plot 1
grid on;
nexttile
plot(y,v); axis square; xlabel('y'); ylabel('v');
xlim([-4,4]); ylim([-4.8,4.8]) %adust the y-limits for plot 2
grid on;
axis('equal') % <- ADDED
end
%------------------------------------------------------------
function dYdt = f(t,Y)
y=Y(1); v=Y(2);
dYdt = [v; 8*sin(t)-4*v-3*y];
end
.
  7 Comments
Alexis
Alexis on 15 Feb 2026 at 5:03
I changed my code so that, instead of 'figure(1)' and 'figure(2)', I just used the word 'figure'. I kept everything the same. Now, it runs. Thank you ALL for your support.
Star Strider
Star Strider on 15 Feb 2026 at 11:40
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

Sign in to comment.

Categories

Find more on 2-D and 3-D Plots in Help Center and File Exchange

Tags

Products


Release

R2025b

Community Treasure Hunt

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

Start Hunting!