Search code examples
matlabplotmatlab-figuresubplot

Matlab. One script cell returns two figures


I'm trying to make a scriptfile with various script cells in it, separated by %%. The following code, returns one an old figure and one circle. However I want to clear the figure window so I only get one figure when I execute one particular script.

% Rita tan(x)
x=((-pi/2)+0.01:0.01:(pi/2)-0.01);
y=tan(x);
plot(x,y)
grid on
%%
% Exempel 1
x=linspace(0,8);
y=x.*sin(x);
plot(x,y)
title('f(x)=sin(x)')
%%
% Plot circle
t=linspace(0,2*pi);
x=cos(t); y=sin(t);
subplot(1,2,1)
plot(x,y)
title('Utan axis equal')
subplot(1,2,2)
plot(x,y)
axis equal
title('Med axis equal')
%%
% Funktionsytor
x=linspace(0,5,50);
y=linspace(0,5,50);
[X,Y]= meshgrid(x,y);
F=X.*cos(2*X).*sin(Y);
surf(X,Y,F)
%%

What I get is:

enter image description here

How do I get only one of them?


Solution

  • Use clf (clear figure) to delete all graphic objects from the current figure. Since it seems likely that you'd be executing scripts in random order, so use clf at the beginning of each section for the stated reason.
    If you're executing the script in the same sequence as shown in the question then you can just add clf at the start of the section after subplots.