下面的程序能画出动画效果。非常实用,注意语法,和line类似,只是前两个必须为xdata与ydata
function h=animline(xdata, ydata, varargin)
% input:
% varargin: properties in line or
% time: time from [xdata(k),ydata(k)] to [xdata(k+1),ydata(k+1)];(两点间绘制的时间)
% gradient: gradual change (渐变效果,数值越大渐变越明显)
% xdata,ydata: vector
% grammar:
% h=animline(xdata, ydata,'Parent',haxes ,'Gradient',10,'Time',1,'Marker','*');
time = 1;
gradient=1;
c={}; % 传入到Line中
for i=1:2:length(varargin)
property=varargin{i};
value=varargin{i+1};
switch(lower(property));
case 'time'
time=value;
case 'gradient'
gradient=value;
otherwise
c=[c,property,value];
end
end
n=length(xdata);
t=time/(gradient);
for k=1:n-1
h=line( 'XData', xdata(1:k),'YData', ydata(1:k) ,c{:});
pause(t); delete(h);
xk=xdata(k); yk=ydata(k);
dx=(xdata(k+1)-xk)/gradient; dy=(ydata(k+1)-yk)/gradient; % step length
for g =1:gradient-1
h=line( 'XData', [xdata(1:k),xk+dx*g],'YData', [ydata(1:k),yk+dy*g] ,c{:});
pause(t); delete(h);
end
end
h=line('XData', xdata,'YData', ydata ,c{:});
下面是另一个版本,使用了drawnow函数
function h=animline(xdata, ydata, varargin)
% input:
% varargin: properties in line or
% time: time from [xdata(k),ydata(k)] to [xdata(k+1),ydata(k+1)];
% gradient: gradual change
% xdata,ydata: vector
% grammar:
% h=animline(xdata, ydata,'Parent',haxes ,'Gradient',10,'Time',1,'Marker','*');
time = 1;
gradient=1;
c={};
for i=1:2:length(varargin)
property=varargin{i};
value=varargin{i+1};
switch(lower(property));
case 'time'
time=value;
case 'gradient'
gradient=value;
otherwise
c=[c,property,value];
end
end
n=length(xdata);
t=time/(gradient);
h=line( 'XData', [],'YData', [] ,c{:});
for k=1:n-1
set(h, 'XData', xdata(1:k),'YData', ydata(1:k));
drawnow; pause(t);
xk=xdata(k); yk=ydata(k);
dx=(xdata(k+1)-xk)/gradient; dy=(ydata(k+1)-yk)/gradient; % step length
for g =1:gradient-1
set(h, 'XData', [xdata(1:k),xk+dx*g],'YData', [ydata(1:k),yk+dy*g]);
drawnow; pause(t);
end
end
set(h,'XData', xdata,'YData', ydata);drawnow;