1

I made a matlab-function that plots a graph. When I call the function several times, I want it to plot all the graphs in one prepared figure. But instead my code opens with every function call the prepared figure in a new window with only one Graph in it.

My function looks like this

function myfunction(x,y)

if ~exist('myfigure')
    myfigure = openfig('myfigure.fig')
    assignin('base', 'myfigure',myfigure) 
end

figure(myfigure);
plot(x,y)

end

With the if-function I tried to prevent it from opening a new figure-window, when myfigure is allready opened. But it seems like Matlab just ignores the if-function for my surprise. Even the Assignin didn't help out. Although checking in the command window, showed that exist('myfigure') changes its value. I really don't know why the if-function is ignored by Matlab. Have you any suggestions how to fix this

crx
  • 153
  • 2
  • 8

2 Answers2

0

The function figure that you used is probably why it opens a new figure.

What you might want to do is simply get the current axes and plot in it.

So your function would look like this

function myfunction(x,y)

myaxes = gca; 
plot(myaxes,x,y)

end

This would work if you only have one active figure and axes, if you have more than you mihgt want to pass the axes handle to the function.

itzik Ben Shabat
  • 927
  • 11
  • 24
  • Sorry I didn't answer within a narrow time frame. – crx Oct 23 '16 at 16:40
  • Your suggestion don't work for my problem cause I prepared a triangle diagramm to plot trinary Datasets and need thus more than the axes. – crx Oct 23 '16 at 16:42
0

The problem here is exist cannot see the previous figure, because it's handle is deleted when the previous call to the function was ended. My suggestion is as follow:

Pass the figure handle to the function, and also return it as output:

function myfigure = myfunction(x,y,myfigure)
if nargin<3 % if you pass 2 variables or less
    myfigure = figure; % create a figure
else
    figure(myfigure); % otherwise use the one in handle
end
plot(x,y)
end

Here a sample code for that:

x = 0:0.01:2*pi;
myfigure = myfunction(x,sin(x)); %first call
myfunction(x,cos(x),myfigure); % second call
myfunction(x,tan(x),myfigure); % third call...

Note that you only need to get myfunction output on the first call, then you can continue using it until you delete the figure.

EBH
  • 10,350
  • 3
  • 34
  • 59
  • Hello @EBH, on the first function call "myfigure" isn't open or defined. So this could not work for me. I now helped me out by omitting the figure code in the function. It has to be entered every time in addition with the function in this way. – crx Oct 23 '16 at 16:49
  • Thank you for your answer. That's totaly what i was looking for. My upvote you maybe not see cause I have less reputation points. One remark for others: after "plot" in the function I had to add "hold on" and you migth not use tan(x) for testing cause it becomes infinite at x=0. – crx Oct 25 '16 at 12:16