xiezhh
2007-08-07, 20:11
猫与耗子相距15(单位不详),耗子以速度20沿墙根往前跑(该墙垂直于猫和耗子的连线),猫以速度40追赶耗子(猫跑的方向一直正对着耗子)。以下是猫追耗子的动画演示程序。
function cat_mouse
clear
clc
mov=avifile('cat_mouse.avi');
ts=0:0.005:0.5;
x0=[0,0];
[t,x]=ode45(@cat_m,ts,x0);
n=length(x);
figure(1)
plot(0,0,'.')
hold on
h1=line( 'Color' ,[0 0 1], 'Marker' , '.' , 'MarkerSize' ,40, 'EraseMode' , 'xor' );
h2=line(15,0,'MarkerFaceColor',[0 1 0],'Marker','h', 'MarkerSize' ,15, 'EraseMode' , 'xor');
plot(15,0,'.')
line([15 15],[0 11],'LineWidth',2)
axis equal
axis([0 16 0 11])
title('猫追耗子动画演示')
for i=1:n-1
plot(x([i i+1],1),x([i i+1],2))
set(h1, 'xdata' ,x(i+1,1), 'ydata' ,x(i+1,2));
set(h2, 'xdata' ,15, 'ydata' ,20*t(i+1));
drawnow; % 刷新屏幕
pause(0.005)
f=getframe(gcf);
mov=addframe(mov,f);
end
hold off
mov=close(mov);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 微分方程组 %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function dx=cat_m(t,x)
a=20;b=40;c=15;
s=sqrt((c-x(1))^2+(a*t-x(2))^2);
dx=[b*(c-x(1))/s;b*(a*t-x(2))/s];
function cat_mouse
clear
clc
mov=avifile('cat_mouse.avi');
ts=0:0.005:0.5;
x0=[0,0];
[t,x]=ode45(@cat_m,ts,x0);
n=length(x);
figure(1)
plot(0,0,'.')
hold on
h1=line( 'Color' ,[0 0 1], 'Marker' , '.' , 'MarkerSize' ,40, 'EraseMode' , 'xor' );
h2=line(15,0,'MarkerFaceColor',[0 1 0],'Marker','h', 'MarkerSize' ,15, 'EraseMode' , 'xor');
plot(15,0,'.')
line([15 15],[0 11],'LineWidth',2)
axis equal
axis([0 16 0 11])
title('猫追耗子动画演示')
for i=1:n-1
plot(x([i i+1],1),x([i i+1],2))
set(h1, 'xdata' ,x(i+1,1), 'ydata' ,x(i+1,2));
set(h2, 'xdata' ,15, 'ydata' ,20*t(i+1));
drawnow; % 刷新屏幕
pause(0.005)
f=getframe(gcf);
mov=addframe(mov,f);
end
hold off
mov=close(mov);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% 微分方程组 %%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function dx=cat_m(t,x)
a=20;b=40;c=15;
s=sqrt((c-x(1))^2+(a*t-x(2))^2);
dx=[b*(c-x(1))/s;b*(a*t-x(2))/s];