Parseval
Parseval

Reputation: 833

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?

Upvotes: 2

Views: 126

Answers (2)

gnovice
gnovice

Reputation: 125854

When the last section is executed, the axes defined by the command subplot(1,2,2) is still the current axes, so that is where your next plot is added. You can close the previous (i.e. current) figure at the beginning of that last section so that a new figure and axes is created for the next plot:

% Funktionsytor
close(gcf);
x=linspace(0,5,50);
...

In general, when dealing with a lot of different figures or axes, best practice dictates that you should store unique handles for each of them. That way you can specifically modify/close them as needed. For example, you could plot your two subplots in two separate figures like so:

%%
% Plot circle

t = linspace(0, 2*pi);
x = cos(t);
y = sin(t);

hFigure1 = figure();  % Create first figure
plot(x, y);           % Plot to axes in first figure
title('Utan axis equal');

hFigure2 = figure();  % Create second figure
plot(x, y);           % Plot to axes in second figure
axis equal;
title('Med axis equal');

Now, you can close either one, or both, as needed later in your code:

close(hFigure1);  % Closes the first figure, second still exists

Upvotes: 2

Sardar Usama
Sardar Usama

Reputation: 19689

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.

Upvotes: 1

Related Questions