MATLAB 从循环中绘制 x,y
我想知道为什么这两个代码不会产生相同的情节?
代码 1:
x=[2,5,7];
y=[10,4,3];
plot(x,y);
代码 2:
x=[2,5,7];
y=[10,4,3];
for i=1:length(x)
xx=x(i);
yy=y(i);
plot(xx,yy);
end
已编辑: 如何使 Code 2
的输出与 Code 1
中的输出类似
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
代码 1
您正在使用
plot(x,y) 向量中定义的
命令。默认情况下,它表示x
和y
坐标绘制一条线plot(x,y,'-');
,这意味着您绘制一条线 (-
)。代码 2
您正在绘制存储在向量中的各个点(无线),因为您为每个点调用
plot
(xx
,yy
)您可以在代码 1 中复制代码 2 中的效果,并进行以下更改:
这会强制 MATLAB 仅绘制点,而不绘制连接线
(如果您想要点和) > 行,
有关更多详细信息,请查看 的文档
plot
命令。示例代码:
Code 1
You're drawing a line with the
x
andy
coordinates defined in the vectors with theplot(x,y)
command. By default, it meansplot(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:
This forces MATLAB to only plot the points and not the connecting line
If you want the points and the line,
For more details, check out the documentation of the
plot
command.Sample Code:
Jacob 的答案解决了两段代码给出不同结果的原因。为了回应您关于绘图时需要循环读取
x
和y
的评论,这里有一个解决方案,它允许您使用使用读取的每个值来更新绘图线GET 和 SET 命令:如果您不打算循环特定次数,但是只是想在某些条件成立时循环,您可以使用 WHILE 循环而不是 FOR环形。
Jacob's answer addresses why the two pieces of code give different results. In response to your comment about needing to read
x
andy
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: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.