Search code examples
matlabfor-loopplotwindowmatlab-figure

Update plot using hold on inside a for loop


I'm combining two plots using this code

plot(x1,y1,'.','MarkerSize',20,'Color','r');
hold on; grid on;
plot(x2,y2,'x','MarkerSize',10,'Color','b');

xlim([-a a]);
ylim([-a a]);

Now I want to change the values of x1,y1 and x2,y2 in order to have more than one point and one cross inside my figure. I tried to use a for loop where I compute new values, but every iteration this code generates another figure - whereas I want just one figure with all the points in it.

I did something like this:

for i=1:1:8
    % do things that compute x1,x2,y1,y2
    figure; hold on
    plot(x1,y1,'.','MarkerSize',20,'Color','r');
    hold on; grid on;
    plot(x2,y2,'x','MarkerSize',10,'Color','b');
    xlim([-a a]);ylim([-a a]);
    i=i+1;
end

I also tried to put the hold on just before i=i+1 but still give me a new figure.


Solution

  • There are several things you can do:

    1. The simple solution would be to put the figure command outside the loop:

      figure(); hold on;
      for ...
        plot(x1, ...);
        plot(x2, ...);
      end
      
    2. A better solution would be to first compute all values and then plot them:

      [x1,y1,x2,y2] = deal(NaN(8,1));
      for ind1 = 1:8
        % do some computations
        x1(ind1) = ...
        ...
        y2(ind1) = ...
      end
      figure(); plot(x1,y1,'.',x2,y2,'x');
      
    3. The best solution (in my opinion) would be to update existing plot objects with new data points as they become available:

      [x1,y1,x2,y2] = deal(NaN(8,1));
      figure(); hP = plot(x1,y1,'.',x2,y2,'x');
      for ind1 = 1:8
        % do some computations
        hP(1).XData(ind1) = <newly-computed x1>
        hP(1).YData(ind1) = <newly-computed y1>
        hP(2).XData(ind1) = <newly-computed x2>
        hP(2).YData(ind1) = <newly-computed y2>
      end