Lakshmi Narayanan
Lakshmi Narayanan

Reputation: 5362

plot hold for plot3 matlab

There is a similar question, to which the answer was given. My question is the same as this one, except, I have 2 loops instead of one as showed there. Still, the solution does't seem to work for me.

The question : How to hold a plot when using plot3 in matlab?

Here, there is a single loop ad the solution seems to work fine. The following is my code :

  figure(1)
  for i = 1:n
      for j = 1:m
         if(condition)
              %some calculations to get X
              x = X(1,:);
              y = X(2,:);
              z = X(3,:);
              plot3(x,y,z,'.');
              view(3);
              hold on;
         end
      end
      hold on;
   end

Here, after all iterations of the inner loop using 'j', am getting a proper plot, but once it goes to the outer loop, the plot refreshes and starts again. How can I maintain the plot3 for both the loops? I have used hold on again in the outer loop, but it still doesn't seem to work. Can anyone tell me how I can maintain the plot for 2 loops.? Thanks in advance.

Upvotes: 0

Views: 2108

Answers (1)

Pursuit
Pursuit

Reputation: 12345

I think that your code should work as is. However, a few changes I would make, which should help whatever problem that you are having:

  1. hold on only needs to be called once.
  2. view(3) also only needs to be called once (actually is not needed at all to get the data plotted, just helps with the visualization).
  3. When I'm performing complex plotting, I usually need to specify the axis to plot on explicitly. Otherwise the plot goes to the "current" axis, which can be changed by some operations. (Depends what you are doing in your calculations.)
  4. A common problem when it looks like data is not being added to a plot is axis scaling. You can use axis tight for a decent first guess at scaling the axis limits.

Putting this together, try this, and see what happens:

%Set up figure to catch plots
figure(1);
hAxis = gca;  %This will create an axis in the figure, and return its handle
hold on;      %You can also use hold(hAxis,'on') if you are really paranoid about which axis is catching your commands

%Perform plots
for i = 1:n
    for j = 1:m
       if (condition)
            %some calculations to get X
            x = X(1,:);
            y = X(2,:);
            z = X(3,:);
            plot3(hAxis,x,y,z,'.');
       end
    end
 end

 %Adjust view etc (experiment here after the data is plotted)
 view(3)
 axis tight

Upvotes: 3

Related Questions