登录论坛

查看完整版本 : MATLAB从Loop绘制x,y


poster
2019-12-10, 20:41
我不知道为什么这两个代码不会产生相同的情节?

代码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输出



回答:

代码1

您正在使用plot(x,y)命令用向量中定义的x和y坐标绘制一条线 。默认情况下,它表示plot(x,y,'-');这表示您画一条线( - )。

代码2

由于要为每个点( xx , yy )调用plot ,因此您正在绘制存储在向量中的单个点(无线)。

您可以通过以下更改在代码1的代码2中复制效果:

plot(x,y,'.'); 这迫使MATLAB仅绘制点而不是连接线

如果要点和线,

plot(x,y,'-.'); 有关更多详细信息,请查看plot (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/plot.html)命令的文档。

样例代码:

%# 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);

更多&回答... (https://stackoverflow.com/questions/3219739)