高尔顿钉板实验的matlab代码动画演示

代码中的n,T,delay等参数均可调,但是过大的时候可能画出来的图不太好看。演示效果大致如下:
在这里插入图片描述

慢速的动画版代码
n=10;T=10;delay=0.2;
count=zeros(1,n);
f1=figure;f2=figure;
if mod(n,2)==1 
    left=-floor(n/2);right=floor(n/2);
else
    left=-n/2;right=n/2-1;
end
pause(1);
for k=1:T
    figure(f1);
    clf;
    for i=1:n
      text(-i+n/2+0.5,0.5,int2str(count(i)),'Color','red','FontSize',14);%计数
    end
    x=[];y=[];
    for i=n:-1:1
        x=[x,(-i:2:i)/2];
        y=[y,zeros(1,i+1)+n+1-i];%计算钉子坐标
    end
    figure(f1);hold on;
    scatter(x,y+0.15,'ok','filled');%画钉子
    r=round(rand(1,n-1)).*2-1;
    xx=0;
    for i=n-1:-1:1
        xx=xx+r(i);
        figure(f1);
        scatter(xx/2,i+0.5,160,'oy','filled');%画乒乓球
        pause(delay);
    end
    text(xx/2,0.5,int2str(count(-xx/2+(n+1)/2)),'Color','white','FontSize',14);%擦除原有的数字
    count(-xx/2+(n+1)/2)=count(-xx/2+(n+1)/2)+1; %该位置自增
    text(xx/2,0.5,int2str(count(-xx/2+(n+1)/2)),'Color','red','FontSize',14);%写更新的数字
    figure(f2);
    bar(left:right,count(n:-1:1));%更新直方图
    text(left,max(count),"t="+k,'Color','black','FontSize',14);
    pause(delay*2);
end
figure(f1);
text(left,n-1,"n="+n+" T="+T,'Color','black','FontSize',14);
hold off
快速的计算演示代码
n=15;T=10000;
count=zeros(1,n);
x=[];y=[];
for i=n:-1:1
    x=[x,(-i:2:i)/2];
    y=[y,zeros(1,i+1)+n+1-i];%计算钉子坐标
end
for k=1:T
    r=round(rand(1,n-1)).*2-1;
    xx=sum(r);
    count(-xx/2+(n+1)/2)=count(-xx/2+(n+1)/2)+1; %该位置自增
end
if n<30
    f1=figure;figure(f1);
    scatter(x,y+0.15,'ok','filled');%画钉子
    for i=1:n
      text(-i+n/2+0.1,0.5,int2str(count(i)),'Color','red','FontSize',8);%显示计数
    end
    text(-(n-1)/2,n,"n="+n+" T="+T,'Color','black','FontSize',14);%显示测试参数
end
f2=figure;figure(f2);
bar(-(n-1)/2:(n-1)/2,count(n:-1:1));%画直方图
text(-(n-1)/2,max(count),"n="+n+" T="+T,'Color','black','FontSize',14);%显示测试参数
hold off
  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值