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

39 visualizaciones (últimos 30 días)
Alexis
Alexis el 15 de Feb. de 2026 a las 0:33
Comentada: Star Strider el 15 de Feb. de 2026 a las 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.

Respuestas (1)

Star Strider
Star Strider el 15 de Feb. de 2026 a las 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 comentarios
Alexis
Alexis el 15 de Feb. de 2026 a las 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 el 15 de Feb. de 2026 a las 11:40
My pleasure!
If my Answer helped you solve your problem, please Accept it!
.

Iniciar sesión para comentar.

Categorías

Más información sobre 2-D and 3-D Plots en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2025b

Community Treasure Hunt

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

Start Hunting!

Translated by