简体   繁体   English

在 MATLAB 中使用 for 循环绘制图形

[英]Plotting graph using for loop in MATLAB

I'm trying to plot a simple graph using for loop as shown below我正在尝试使用 for 循环绘制一个简单的图形,如下所示

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?这是为什么?

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.使用plot(x(i),y)绘制 100 个单点(每次迭代中一个),默认情况下不显示。 Therefore the plot looks empty.因此,情节看起来是空的。


Solution 1: Vectorized calculation and direct plot方案一:矢量化计算和直接绘图

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.在这种情况下,不需要 for 循环,因为您可以直接在 MATLAB 中计算和绘制向量。 So the following code does probably what you want:所以下面的代码可能会做你想要的:

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

Note that y is a vector as well as x and that y(n) equals to sin(x(n)) for all n .请注意, y是向量以及x并且y(n)等于所有n sin(x(n)) If you want to plot the points itself, use LineSpec -syntax when calling plot like this 1 :如果要绘制点本身,请在调用plot时使用LineSpec -syntax 1

plot(x,y,'*');

1) Other types of points are possible as well, see the above linked documentation. 1) 其他类型的点也是可能的,请参阅上面的链接文档。


Solution 2: Calculate values within for-loop and plot afterwards解决方案 2:计算 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.如果您想计算 for 循环中的值并在之后绘制它:预先分配所需的变量(在本例中为y ),计算 for 循环中的值,最后在计算后用一个命令绘制它。

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

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

plot(x,y);

Solution 3: Dynamically update plot while calculating解决方案 3:计算时动态更新绘图

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.如果您坚持在每次迭代中绘图,解决方案 2 中的先前代码可以扩展如下:创建一个图形,向其添加一个“空”图并存储其句柄。 Within the for-loop calculate the values and add them to the y -vector as shown above.在 for 循环中计算值并将它们添加到y向量中,如上所示。 As a last step you can update the plot by changing its XData and YData properties and calling drawnow .作为最后一步,您可以通过更改其XDataYData属性并调用drawnow来更新绘图。 Note that calling plot every time within the for-loop is unnecessarily expensive and I don't recommend it.请注意,每次在 for 循环中调用plot都是不必要的昂贵,我不建议这样做。

% 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

Simple approach简单的方法

If you want to draw a curve as you add data, try the following:如果要在添加数据时绘制曲线,请尝试以下操作:

x = linspace(0,2 * pi, 100);
y = zeros(size(x));
for i=1:numel(x)
     y(i) = sin(x(i));
     plot(x(1:i), y(1:i), 'color', 'r')
     drawnow();
end

Be aware that the plot automatically tries to set x and y limits (curve is scaled to the plot window), to prevent that you have to manually set the x- and y-limits with xlim and ylim .请注意,绘图会自动尝试设置 x 和 y 限制(曲线缩放到绘图窗口),以防止您必须使用xlimylim手动设置 x 和 y 限制。

As Matt wrote in his answer, calling plot in each iteration is quite expensive (ie time consuming).正如马特在他的回答中所写的那样,在每次迭代中调用plot非常昂贵(即耗时)。 Therefore I suggest using datasources:因此我建议使用数据源:

Update graph using data sources使用数据源更新图表

% Create a panel and axes object
h_panel = uipanel;
h_axes = axes( 'Parent', h_panel);

% Create data sources
x = linspace(0,2 * pi, 100);
y = zeros(size(x));

% Create graph object, in this case stairs 
% and bind the variables x and y as its data sources
h_stairs = stairs(h_axes, x, y, 'XDataSource', 'x', 'YDataSource', 'y');

for i=1:size(x)
    y(i) = sin(x(i));
    % Update the data of the stairs graph
    refreshdata(h_stairs); 
    drawnow();
end

The call to drawnow isn't neccessary in each iteration, it is only used to update the visuals, so you can see the changes directly.在每次迭代中都不需要调用drawnow ,它仅用于更新视觉效果,因此您可以直接看到更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM