在多个Matlab绘图调用期间连接点

在多个Matlab绘图调用期间连接点,matlab,matlab-figure,Matlab,Matlab Figure,我想在多次Matlab绘图调用期间连接两个或多个数据点。下面是一些虚拟代码,显示了我试图实现的目标 function main() close all t = 0; while t<10 x = rand(1,1); y = rand(1,1); t = t+1; calculateErrorAndPlot(1,x,y,t) end return function calculateErrorAndPlot(figureNumber,x,y,time

我想在多次Matlab绘图调用期间连接两个或多个数据点。下面是一些虚拟代码,显示了我试图实现的目标

function main()
close all

t = 0;

while t<10
    x = rand(1,1);
    y = rand(1,1);
    t = t+1;
    calculateErrorAndPlot(1,x,y,t)
end
return


function calculateErrorAndPlot(figureNumber,x,y,time)

    figure(figureNumber); 
    if ~ishold 
        hold on
    end

    error = x-y;
    plot(time,error,'.b');
return
函数main()
全部关闭
t=0;

当t时,我将重写此,并删除该函数:

time = [1:10];

for ii = 1:length(time)
    x = rand(1,1);
    y = rand(1,1);
    error(ii) = x-y;
 end
 plot(time,error,'.-b')
您可以更新已打印线的属性和属性以添加新点。例如:

function main
   fig = figure;
   ax = axes( 'Parent', fig );
   line = plot( NaN, NaN, 'Parent', ax );
   for t = 0:9
      x = rand( 1, 1 );
      y = rand( 1, 1 );
      calculateErrorAndPlot( line, x, y, t )
   end
end

function calculateErrorAndPlot( line, x, y, t )
   xData = get( line, 'XData' );
   yData = get( line, 'YData' );
   xData(end+1) = t;
   yData(end+1) = x - y;
   set( line, 'XData', xData, 'YData', yData );
end

下面是一些有效的代码。但是,我愿意接受更简单和/或更快的建议或其他代码:)


你只是想用一条线连接两点吗?这是你的问题吗?是的,但在问题的上下文中,它不是简单地用一条线连接两个点。与其绘制标量,不如只创建数组。显然,我不知道您的实际代码是什么样子的,但是如果这有帮助,请告诉我。是的,谢谢。上面的代码是我代码的一个代表性示例。我现在不可能提前完成x和y,所以,它们将是标量。这就是我使用随机数生成器的原因。我想有一种选择是得到绘图上的所有x和y点,并将它们作为一条线重新绘制。我不确定什么时候会得到更多的x和y值?但是,如果说你每天得到一个集合,你可以把上面的变量保存到mat文件中,把下一个集合的add/concat保存到现有的变量中。所以,如果错误为=[1,2,5,6],则得到另一组x,y。您可以只加载error并对其进行concat,因此error=[error,newerror]。并相应地调整你的时间。@anr。我很乐意进一步提供帮助,但您需要解释您尝试了什么,以及哪些不起作用。@anr。我最初的回答只是想为您指出使用扩展数据和YData的正确方向。不打算用作复制粘贴解决方案。我现在对它进行了编辑,以便在您的主要功能的上下文中更加完整。我建议在使用此解决方案之前,花一些时间学习和实验这些线属性。
function calculateErrorAndPlot(figureNumber,x,y,time)

figure(figureNumber);
if ~ishold
    hold on
end

error = x-y;

h = findobj(figure(figureNumber),'Type','line');
if isempty(h)
    xx = time;
    yy = error;
else
    xx = [h(1).XData(end) time];
    yy = [h(1).YData(end) error];
end
plot(xx,yy,'.-black');
return