Search code examples
matlabreal-timehandlelineseries

How to plot several curves in MATLAB using handles


I am plotting data in MATLAB in real time. I want to use a handle. My problem is I do not know how to plot more than one Y-Data Curve.

I found the following code It shows how to plot one set of YData. Has anybody got an idea to transform the code into two or more Y-Datasets, e.g. sind(x) as an additional curve in the plot?

x = 1:1000;
y = cosd(x);

xi = x(1);
yi = y(1);
h = plot(xi, yi, 'YDataSource', 'yi', 'XDataSource', 'xi');

for k = 2:1000...
xi = x(1:k);
yi = y(1:k);
refreshdata(h, 'caller');
drawnow;
end;

Solution

  • The below code works for me, if you really want to use handles

    x = 1:1000;
    y = cosd(x);
    y2 = sind(x);
    
    xi = x(1);
    yi = y(1);
    yi2 = y2(1);
    figure(1); clf;
    h = plot(xi, yi, 'YDataSource', 'yi', 'XDataSource', 'xi');
    hold on;
    h2 = plot(xi, yi2, 'YDataSource', 'yi2', 'XDataSource', 'xi');
    
    for k = 200:1000
        xi = x(1:k);
        yi = y(1:k);
        yi2 = y2(1:k);
        refreshdata(h);
        refreshdata(h2);
        drawnow;
    end;
    

    You do need a hold on.

    Also, instead of refreshdata you can use set as Andrey suggested:

    set(h,'Xdata',xi,'YData',yi);
    set(h2,'Xdata',xi,'YData',yi2);