小球随机游走
模型讲解
初始位置2||3||4
1/3概率前进、后退、不动(一次一步)
位置1只能前进至2
位置5只能后退至4
详细见代码
低阶代码
function ballmove
clear
clc
close all
%%
% 静态图形预设
figure ('Color',[1 1 1])%白色背景
hold on
axis off%关闭坐标轴
axis equal%控制线段输出尺寸
plot([1,5],[0,0])
for i=1:5
plot ([i i],[0,0.1]);%'Color','b'固定颜色
text(i-0.03,-0.1,num2str(i))
end
x0=randi([2,4]);
h=plot(x0,0,'c.','MarkerSize',40);
dx=0.008;
%循环100次
for i=1:100
if x0==1
x1=2;
elseif x0==5
x1=4;
else
p=randi([1,3]);
if p==1
x1=x0+1;
elseif p==2
x1=x0;
elseif p==3
x1=x0-1;
end
end
if x1<x0
while x1<x0
x0=x0-dx;
set(h,'XData',x0);
drawnow
end
x0=x1;
set(h,'XData',x0);
drawnow
elseif x1==x0
pause(0.5)
elseif x1>x0
while x1>x0
x0=x0+dx;
set(h,'XData',x0);
drawnow
end
x0=x1;
set(h,'XData',x0);
drawnow
end
end
效果图:
高阶代码(+计数功能)
声明:
在低阶基础上加上小球到达位置1或位置5的次数统计
function draw_ballmove
clear
clc
close all
%%
% 静态图形预设
figure ('Color',[1 1 1])%白色背景
hold on
axis off%关闭坐标轴
axis equal%控制线段输出尺寸
plot([1,5],[0,0])
for i=1:5
plot ([i i],[0,0.1]);%'Color','b'可以固定颜色
text(i-0.03,-0.1,num2str(i))
end
x0=randi([2,4]);
h=plot(x0,0,'c.','MarkerSize',40);
dx=0.005;
count1=0;
count5=0;
t1=text(1-0.03,0.2,num2str(count1));
t5=text(5-0.03,0.2,num2str(count5));
%%
%循环30次
for k=1:30
if x0==1
count1=count1+1;
plot(1,0,'.','MarkerSize',40);
%两种方法动态显示count1变化
%————1
% set(t1,'Visible','off');
% t1=text(1-0.03,0.2,num2str(count1));
%————2
set(t1,'String',num2str(count1));
x0=randi([2,4]);
elseif x0==5
count5=count5+1;
plot(5,0,'.','MarkerSize',40);
set(t5,'String',num2str(count5));
x0=randi([2,4]);
end
%%
p=randi([1,3]);
if p==1
x1=x0+1;
elseif p==2
x1=x0;
elseif p==3
x1=x0-1;
end
%%
if x1<x0
for j=x0:-dx:x1
set(h,'XData',j)
drawnow
end
elseif x1==x0
pause(0.5)
elseif x1>x0
for i=x0:dx:x1
set(h,'XData',i)
drawnow
end
end
x0=x1;
end
效果图: