如何在一个图中绘制几个函数调用

时间:2016-10-22 02:48:42

标签: matlab function plot matlab-figure

我制作了一个绘制图形的matlab函数。当我多次调用该函数时,我希望它将所有图形绘制在一个准备好的图中。但是我的代码会打开,每个函数都会在新窗口中调用准备好的图形,其中只有一个图形。

我的功能看起来像这样

function myfunction(x,y)

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

figure(myfigure);
plot(x,y)

end

使用if-function我试图阻止它打开一个新的图形窗口,当myfigure全部打开时。但看起来Matlab似乎忽略了if-function让我感到惊讶。即使是Assignin也没有帮助。虽然检查命令窗口,但显示存在(' myfigure')更改其值。 我真的不知道为什么matlab会忽略if函数。您有任何建议如何解决此问题

2 个答案:

答案 0 :(得分:0)

您使用的函数figure可能就是为什么它会打开一个新的数字。

您可能想要做的只是获取当前轴并在其中绘图。

所以你的功能看起来像这样

function myfunction(x,y)

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

end

如果您只有一个活动的数字和轴,如果您想要将轴手柄传递给该函数,则可以使用。

答案 1 :(得分:0)

这里的问题是exist无法看到上一个图,因为当前一个函数调用结束时,它的句柄被删除了。我的建议如下:

将数字句柄传递给函数,并将其作为输出返回:

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

这是一个示例代码:

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...

请注意,您只需要在第一次调用时获得myfunction输出,然后您可以继续使用它直到删除该数字。