1.要求
小球在如下图5个点间移动,其下一个位置有一下几种情况:
- 如果当前在最左侧位置,即x=1,则下一次到x=2位置处;
- 如果当前在最右侧位置,即x=5,则下一次到x=4位置处;
- 如果当前在x=2/x=3/x=4位置,则下一次各有三分之一的概率向左移动一格、向右移动一格、保持不动。
2.matlab代码
clear;
close all;
clc;
speed = 4; %速度
marksize = 30;
speed_fan = 1/speed;%取反
x=1:0.01:5;%x轴
y=ones(size(x));%y轴
pos = [1, 2, 3, 4, 5];%五个位置
next = randi(length(pos));%初始位置
fig = figure('CloseRequestFcn',@my_closereq);%图窗
plot(x,y, 'b-', 'linewidth', 2);%线
hold on;
axis equal;
axis off;
for t=1:length(pos)
plot([pos(t), pos(t)],[1, 1.1],'b', 'linewidth', 2);%点
text(t-0.03, 0.9, num2str(t));
hold on;
end
global flag
flag = 1;%标记是否关闭
while flag
pre = next;
if or(or(next==2, next==3), next==4)%2,3,4位置
t = randi(3);
if t==1%左移
next = next -1;
elseif t==3%右移
next = next + 1;
end
elseif next==1%右移
next = 2;
else%左移
next = 4;
end
for move=linspace(pre, next,100)%游动
h = plot(move,1,'r.', 'markersize',marksize);
pause(speed_fan*0.01);%游动暂停
set(h,'Visible','off');
delete(h);
end
h = plot(next,1,'r.', 'markersize',marksize);%最后位置
hold on;
% pause(speed_fan*1);%暂停
if flag==1
set(h,'Visible','off');%删除
delete(h);
end
end
function my_closereq(~,~)%关闭图窗按钮
global flag
delete(gcf)
flag = 0;%关闭标志
return
end
实现效果:
演示视频:
3.升级
- 实时显示到达边界的次数,两个边界各分别显示;
- 到达最右侧边界后,下一次跳到随机位置。
4.matlab实现
clear;
close all;
clc;
speed = 4; %速度
marksize = 30;
speed_fan = 1/speed;%取反
x=1:0.01:5;%x轴
y=ones(size(x));%y轴
pos = [1, 2, 3, 4, 5];%五个位置
num = zeros(1,2);
sum_num1 = 0;
sum_num = 0;
next = randi(length(pos));%初始位置
fig = figure('CloseRequestFcn',@my_closereq);%图窗
plot(x,y, 'b-', 'linewidth', 2);%线
hold on;
axis equal;
axis off;
for t=1:length(pos)
plot([pos(t), pos(t)],[1, 1.1],'b', 'linewidth', 2);%点
text(t-0.03, 0.9, num2str(t));
hold on;
end
h = plot(next,1,'r.', 'markersize',marksize);
text_num = text(5-0.03, 1.3, num2str(sum_num));
text_num1 = text(1-0.03, 1.3, num2str(sum_num1));
hold on;
global flag
flag = 1;%标记是否关闭
while flag
if sum(num)==2
num = zeros(1, 2);
next = randi(length(3)) + 1;
continue;
end
pre = next;
delete(text_num);
delete(text_num1);
text_num = text(5-0.03, 1.3, num2str(sum_num));
text_num1 = text(1-0.03, 1.3, num2str(sum_num1));
if or(or(next==2, next==3), next==4)%2,3,4位置
t = randi(3);
if t==1%左移
next = next -1;
elseif t==3%右移
next = next + 1;
end
elseif next==1%右移
next = 2;
else%左移
next = 4;
continue;
end
for move=linspace(pre, next,100)%游动
set(h, 'xdata', move);
pause(speed_fan*0.01);%游动暂停
end
set(h, 'xdata', next);
if next==1
num(next) = 1;
sum_num1 = sum_num1 + 1;
elseif next==5
num(2) = 1;
sum_num = sum_num + 1;
end
hold on;
end
function my_closereq(~,~)%关闭图窗按钮
global flag
delete(gcf)
flag = 0;%关闭标志
out = 1
return
end
实现效果:
演示视频: