MATLAB plot x,y from Loop
I wonder why these two code doe开发者_运维技巧sn'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
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'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.
精彩评论