Search code examples
matlabmatlab-figure

connect points during multiple Matlab plot calls


I would like to connect two or multiple data points during multiple Matlab plot calls. Below is some dummy code that shows what I am trying to accomplish,

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

Right now, I have to use '.b' to at least see the data points being plotted. Note that plot is being called with scalars.


Solution

  • Here is some code that works. However, I am open to suggestions or other code that may be simpler and/or faster :)

    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