0

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.

1 Answer 1

2

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
    
Sign up to request clarification or add additional context in comments.

2 Comments

Is it possible change color of the dot and the cross for each iteration? In order to have dot and cross of the same color for the first iteration, another color for the next and so on...
@Shika93 Yes, it's possible. However, changing your question or adding new requirements after it has been answered is frowned-upon on SO. Specifically, getting this to work would make my 2nd and 3rd suggestions invalid. Feel free to ask a new question and add a link to this Q&A if it helps provide context. If you decide to ask a new question, please explain how you want the colors to change with each iteration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.