这是使用该函数为其设置动画的一种方法POLYFIT http://www.mathworks.com/access/helpdesk/help/techdoc/ref/polyfit.html拟合抛物线x
and y
, 功能POLYVAL http://www.mathworks.com/access/helpdesk/help/techdoc/ref/polyval.html评估你的多项式在一组x
价值观,以及SET http://www.mathworks.com/access/helpdesk/help/techdoc/ref/set.html命令修改绘图对象而不必重新绘制它们:
load objects.mat %# Load the data
x = objects(:,1); %# Get the x data
y = objects(:,2); %# Get the y data
N = numel(x); %# The number of points
hPoints = plot(x(1),y(1),'r*'); %# Plot first point as a red asterisk,
%# saving the handle
hold on; %# Add to the plot
hFitLine = plot(x,nan(N,1),'b-'); %# Initialize the plot for the fit line,
%# saving the handle and using NaN for
%# the y values so it doesn't appear yet
axis([min(x) max(x) min(y) max(y)]); %# Set the axis limits
for k = 1:N
set(hPoints,'XData',x(1:k),'YData',y(1:k)); %# Update the points
if k >= 15 %# Plot a fit line starting at k = 15
p = polyfit(x(1:k),y(1:k),2); %# Fit a parabola with points 1 through k
yFit = polyval(p,x); %# Evaluate the polynomial at all x
set(hFitLine,'YData',yFit); %# Update the fit line
end
drawnow(); %# Force the plot to refresh
pause(0.25); %# Pause for a quarter second
end
关于 MATLAB 图形的注释...
任何时候发出绘图命令(例如PLOT http://www.mathworks.com/access/helpdesk/help/techdoc/ref/plot.html),然后是一个或多个处理图形对象 http://www.mathworks.com/access/helpdesk/help/techdoc/learn_matlab/f3-15974.html在当前轴中创建。这些对象有一个“句柄”或数字标识符,充当绘图对象的引用,并可用于访问和修改对象的属性。这GET http://www.mathworks.com/access/helpdesk/help/techdoc/ref/get.html and SET http://www.mathworks.com/access/helpdesk/help/techdoc/ref/set.html命令可用于分别使用其句柄访问和修改图形对象的属性,这些句柄通常作为绘图命令的输出参数返回。
每种类型的句柄图形对象都有一组属性。这PLOT http://www.mathworks.com/access/helpdesk/help/techdoc/ref/plot.html命令创建一个lineseries
具有许多可以找到的属性的对象here http://www.mathworks.com/access/helpdesk/help/techdoc/ref/lineseriesproperties.html。例如,'XData'财产 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/lineseriesproperties.html#XData存储绘制点的 x 值,而'YData'财产 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/lineseriesproperties.html#YData存储 y 值。您可以通过修改这些属性来更改绘制点的 x 和 y 位置lineseries
object.
在 MATLAB 中对图形进行动画处理时,首先创建对象并在动画过程中更新其属性通常比在动画过程中创建、删除然后重新创建对象更有效。在上面的代码中,在动画循环之前创建各个点的绘图对象,并且该对象的句柄存储在变量中hPoints
。抛物线的绘图对象也在动画循环之前创建,其句柄存储在hFitLine
。然后,SET http://www.mathworks.com/access/helpdesk/help/techdoc/ref/set.html命令在循环中用于修改这两个绘图对象。
由于抛物线一开始是不可见的,因此将初始 y 值设置为全部NaN http://www.mathworks.com/access/helpdesk/help/techdoc/ref/nan.html导致线条无法渲染(尽管对象仍然存在)。您还可以通过设置它来使该线不可见'Visible'财产 http://www.mathworks.com/access/helpdesk/help/techdoc/ref/lineseriesproperties.html#Visible to 'off'
.