在 MATLAB 中使用 for 循环绘制图形 [英] Plotting graph using for loop in MATLAB

查看:793
本文介绍了在 MATLAB 中使用 for 循环绘制图形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 for 循环绘制一个简单的图形,如下所示

I'm trying to plot a simple graph using for loop as shown below

x=linspace(0,2*pi,100);
for i=1:numel(x)
    y=sin(x(i));
    plot(x(i),y)
    hold on
end

然而,我的图上没有任何东西出现.这是为什么?

However, nothing appear on my figure. Why is that?

推荐答案

为什么会这样...

使用 plot(x(i),y) 您将绘制 100 个单点(每次迭代中一个)并且默认情况下不会显示它们.因此,情节看起来是空的.

Why this happens...

With plot(x(i),y) you are plotting 100 single points (one in each iteration) and they are not shown by default. Therefore the plot looks empty.

我假设您打算画一条连续的线.在这种情况下,不需要 for 循环,因为您可以直接在 MATLAB 中计算和绘制向量.所以下面的代码可能会做你想要的:

I assume you meant to draw a continuous line. In that case no for-loop is needed because you can calculate and plot vectors directly in MATLAB. So the following code does probably what you want:

x = linspace(0,2*pi,100);
y = sin(x);
plot(x,y);

注意 yx 一样是一个向量,并且 y(n) 等于 sin(x(n))) 用于所有 n.如果您想自己绘制点,请使用 LineSpec- 像这样调用 plot 时的语法1:

Note that y is a vector as well as x and that y(n) equals to sin(x(n)) for all n. If you want to plot the points itself, use LineSpec-syntax when calling plot like this1:

plot(x,y,'*');

1) 其他类型的点也是可能的,请参阅上面链接的文档.

如果您想计算 for 循环中的值并在之后绘制它:预先分配所需的变量(在本例中为 y),计算 for 循环中的值,最后计算后用一个命令绘制它.

If you want to calculate the values within a for-loop and plot it afterwards: Pre-allocate the needed variable (in this case y), calculate the values within the for-loop and finally plot it with one single command after the calculation.

x = linspace(0,2*pi,100);

y = zeros(size(x));
for i = 1:numel(x)
    y(i) = sin(x(i));
end

plot(x,y);


解决方案 3:计算时动态更新图

如果您坚持在每次迭代中绘图,解决方案 2 中的先前代码可以扩展如下:创建一个图形,向其添加一个空"图并存储其句柄.在 for 循环中计算值并将它们添加到 y-vector,如上所示.作为最后一步,您可以通过更改其 XDataYData 属性并调用 drawnow 来更新绘图.请注意,每次在 for 循环中调用 plot 都不必要地昂贵,我不推荐这样做.


Solution 3: Dynamically update plot while calculating

In case you insist on plotting within each iteration, the previous code from Solution 2 can be expanded as follows: Create a figure, add an 'empty' plot to it and store its handle. Within the for-loop calculate the values and add them to the y-vector as shown above. As a last step you can update the plot by changing its XData and YData properties and calling drawnow. Note that calling plot every time within the for-loop is unnecessarily expensive and I don't recommend it.

% create figure and plot
figure;
ph = plot(0,0);
ax = gca;
set(ax,'XLim',[0,2*pi]);
set(ax,'YLim',[-1,1]);

% calculate and update plot
x = linspace(0,2*pi,100);
y = zeros(size(x));
for i = 1:numel(x)
    y(i) = sin(x(i));
    set(ph,'XData',x(1:i));
    set(ph,'YData',y(1:i));
    drawnow;
end

这篇关于在 MATLAB 中使用 for 循环绘制图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆