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

조회 수: 42 (최근 30일)
Alexis
Alexis 2026년 2월 15일 0:33
댓글: Star Strider 2026년 2월 15일 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.

답변 (1개)

Star Strider
Star Strider 2026년 2월 15일 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
Alexis
Alexis 2026년 2월 15일 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 2026년 2월 15일 11:40
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 2-D and 3-D Plots에 대해 자세히 알아보기

태그

제품


릴리스

R2025b

Community Treasure Hunt

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

Start Hunting!

Translated by