views:

53

answers:

2

I wonder why these two code doesn't produce the same plot?

code 1:

x=[2,5,7];
y=[10,4,3];
plot(x,y);

code 2:

x=[2,5,7];
y=[10,4,3];

for i=1:length(x)
    xx=x(i);
    yy=y(i);
    plot(xx,yy);

end

EDITED: How I can make the output of Code 2 similar to output in Code 1

+3  A: 

Code 1

You're drawing a line with the x and y coordinates defined in the vectors with the plot(x,y) command. By default, it means plot(x,y,'-'); which means you draw a line (-).

Code 2

You're drawing individual points (no line) stored in the vectors since you're calling plot for each point (xx,yy)

You can duplicate the effect in Code 2 in Code 1, with the following change:

plot(x,y,'.');

This forces MATLAB to only plot the points and not the connecting line

If you want the points and the line,

plot(x,y,'-.');

For more details, check out the documentation of the plot command.

Sample Code:

%# If you know the number of elements, preallocate
%# else just initialize xx = []; and yy =[];
xx = zeros(100,1);
yy = zeros(100,1);

%# Get the data
for i = 1:length(xx)
    xx(i) = getXSomehow();
    yy(i) = getYSomehow();
end

%# Plot the data
plot(xx,yy);
Jacob
Jacob@ Thanks, but actually for some reasons I have need to read the x and y through loop and I want to produce the output as in Code 1. Is it possible to do that?
Jessy
No, you'll have to store it in a vector and then plot it.
Jacob
+1 for referring to docs
rubenvb
+2  A: 

Jacob's answer addresses why the two pieces of code give different results. In response to your comment about needing to read x and y in a loop while plotting, here's one solution that will allow you to update the plot line with each value read using the GET and SET commands:

hLine = plot(nan,nan,'-.');  %# Initialize a plot line (points aren't displayed
                             %#   initially because they are NaN)
for i = 1:10                       %# Loop 10 times
  x = ...;                         %# Get your new x value somehow
  y = ...;                         %# Get your new y value somehow
  x = [get(hLine,'XData') x];      %# Append new x to existing x data of plot
  y = [get(hLine,'YData') y];      %# Append new y to existing y data of plot
  set(hLine,'XData',x,'YData',y);  %# Update the plot line
  drawnow;                         %# Force the plot to refresh
end

If you aren't going to loop a specific number of times, but simply want to loop while some condition is true, you can use a WHILE loop instead of a FOR loop.

gnovice
Thank you. How I can add some text on the plot showing the sequence of the coordinate? e.g. 1,2,3...n?
Jessy
@Jessy: You can use the [TEXT](http://www.mathworks.com/access/helpdesk/help/techdoc/ref/text.html) function to place text at a given set of coordinates. For example, you could put this in your loop after you read `x` and `y`: `text(x,y,int2str(i));`
gnovice

related questions