multiple graphs in one script

8 ビュー (過去 30 日間)
basim almutairi
basim almutairi 2021 年 9 月 5 日
回答済み: Robert U 2021 年 9 月 6 日
Hey all,
I would like to plot several graphs in one script. However, it keeps giving me the last graph one. please see below code
%% 6
x = ([-2*pi:0.1:2*pi]);
f = x-sin(x)
g = 1-x.*cos(x)
plot(x,f,x,g)
title('f(x) & g(x)')
subplot(1,2,1)
plot(x,f)
title('f(x)')
subplot(1,2,2)
plot(x,g)
title('g(x)')
what is the wrong here

回答 (2 件)

Wan Ji
Wan Ji 2021 年 9 月 5 日
Modified the code as
%% 6
x = ([-2*pi:0.1:2*pi]);
f = x-sin(x)
g = 1-x.*cos(x)
figure(1);clf;
plot(x,f,x,g)
title('f(x) & g(x)')
figure(2);clf;
subplot(1,2,1)
plot(x,f)
title('f(x)')
subplot(1,2,2)
plot(x,g)
title('g(x)')

Robert U
Robert U 2021 年 9 月 6 日
Hi basim almutairi,
Simplify your life and use handles (start here: graphics-objects): figure handles, axes handles, ...
Handles allow to modify properties even later in code. It makes it easier to debug and to modify plots.
x = (-2*pi:0.1:2*pi);
f = x-sin(x);
g = 1-x.*cos(x);
fh{1} = figure(1);
ah{1} = axes(fh{1});
plot(ah{1},x,f,x,g)
title(ah{1},'f(x) & g(x)')
fh{2} = figure(2);
sh{1} = subplot(1,2,1,'Parent',fh{2});
plot(sh{1},x,f)
title(sh{1},'f(x)')
sh{2} = subplot(1,2,2,'Parent',fh{2});
plot(sh{2},x,g)
title(sh{2},'g(x)')
Kind regards,
Robert

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by