Search code examples
matlabplotmatlab-figure

two curves on one figure with one kept updating


I have following code which basically plot the original signal x on the figure, and updates the reconstructed signal rec iteratively.

plot(x); hold on

err = 100; tol = 0.1; err_vec = [];
while err > tol % iterations
    % Low-pass filter xpg
    REC = fft(rec);
    REC(M+2:N-M) = 0;
    rec = real(ifft(REC)); plot(rec, 'r*');  drawnow

    % Restore the known samples    %
    rec(ks) = y(ks);

    % Error
    err = norm(rec - x)
    err_vec = [err_vec err];
end

What I like is to retain x on the figure, and only update rec at each iteartion, such that I can see that rec is gradually approaching x.

However, with my current code, although x is retained, rec from each iteration simply overlaps on the figure, which is annoying. I'd like to show the rec from only current iteration.

How should I change my code to do that?


Solution

  • Beside the suggestion proposed by @excaza, you can try:

    • call the plot function specifying the return value (the handle to the line plotted
    • plot the updated curve
    • call pause in order to "slow` the process
    • call delete to delete the last plotted curve

    A possible implementation, based on two generic curves, could be:

    t=0:.01:2*pi;
    x=sin(t);
    plot(t,x)
    hold on
    grid on
    k=0:.1:1
    for i=1:length(k)
       y=sin(t);
       hp=plot(t,y*k(i),'r')
       legend('Target Curve','Approximate curve')   
       pause(.3)
       delete(hp)
    end
    

    enter image description here