元胞自动机
常用语句:
UIControl
控件设置
参考:
https://ww2.mathworks.cn/help/matlab/ref/matlab.ui.control.uicontrol-properties.html
image
数组绘图
参考:
https://ww2.mathworks.cn/help/matlab/ref/image.html#d120e549133
set(句柄值,属性名,属性值)、get(句柄值,属性名)
用来更改/获取当前对象的属性值。
e.g:
h=plot(x,y1,x,y2,x,y3);
set(h,{‘LineWidth’},{2;5;8}) %设置线宽分别为2,5,8
drawnow/pause(时间间隔)
更新图窗/延迟
常见模型
生命游戏
棋盘状网格中每个方格中居住着一个细胞,细胞下一时刻的状态取决于相邻八个方格中活细胞的数量:
变化规则:
如果周围有两个活细胞,那么细胞状态不改变。
如果周围有三个活细胞,下一时刻细胞状态为活
否则下一时刻细胞死亡
思路:
1.初始化:设置元胞数目,迭代次数,建立元宝矩阵和辅助扩大矩阵等
2.迭代计算:计算邻居状态,更新元胞矩阵,更新辅助扩大矩阵,绘图、暂停
MATLAB代码
%% 界面控制
startbutton=uicontrol('style','pushbutton','string','start','fontsize',12,'position',[100,400,50,20],'callback','start=1;');
freezebutton=uicontrol('style','pushbutton','string','freeze','fontsize',12,'position',[320,400,50,20],'callback','freeze=1;');
quitebutton=uicontrol('style','pushbutton','string','quit','fontsize',12,'position',[400,400,50,20],'callback','stop=1;close;');
number=uicontrol('style','text','string','1','fontsize',12,'position',[20,400,50,20]);
freeze_at_text=uicontrol('style','text','string','freeze at:','fontsize',12,'position',[180,400,80,20],'callback','start=1;');
freeze_at=uicontrol('style','edit','string','1000','fontsize',12,'position',[250,400,50,20]);
%% 初始化设置
n=400;%元胞数目
z=zeros(n,n);
cells=(rand(n,n))<0.6;%初始值随机分布
big_matrix=zeros(n+2,n+2);%增补矩阵
big_matrix(2:end-1,2:end-1)=cells;
imh= image(cat(3,z,z,cells));%建立图像句柄
figure(gcf);
set(gcf,'doublebuffer','on');%双缓冲开启
%% 主循环
start=0; stop=0;freeze=0;
while stop==0
if findobj==0 %用来监视窗口是否已经被关闭 防止报错
break;
end
if start==1
z=zeros(n,n);
sum=sum_neighbour(big_matrix);%计算邻居状态和
z(cells==1&(sum==2|sum==3))=1;%按规则更新状态
z(cells==0&sum==3)=1;
big_matrix(2:end-1,2:end-1)=z;%将新状态填充回增补矩阵
cells=z;%将状态更新
set(imh,'cdata',cat(3,zeros(n,n),zeros(n,n),cells));%画图
stepnumber=1+str2double(get(number,'string'));%更新计数
set(number,'string',num2str(stepnumber));
end
if (freeze==1||stepnumber==str2double(get(freeze_at,'string')))%判断是否暂停
start=0;
freeze=0;
end
drawnow%更新绘图
end
%% 计算邻居和函数
function [A]=sum_neighbour(B)
%元胞自动机 计算周围邻居的状态和
A=B(1:end-2,1:end-2)+...
B(1:end-2,2:end-1)+...
B(1:end-2,3:end)+...
B(2:end-1,1:end-2)+...
B(2:end-1,3:end)+...
B(3:end,1:end-2)+...
B(3:end,2:end-1)+...
B(3:end,3:end);
end
参考
https://blog.csdn.net/ylf12341/article/details/89050030
https://blog.csdn.net/qq_40527086/article/details/86798384
森林火灾&病毒传播
通过生命游戏,对元胞自动机的大致流程应该有了一些基础了。再做森林火灾或者传染病估计基本上就是添添改改的事儿了,这里就不一一写了,贴一些其他博主写好的代码以供参考(犯懒)
参考资料
数学模型关于澳大利亚山火的建模
https://mp.weixin.qq.com/s?__biz=MzI0MDMxMTM0NQ==&mid=2247484533&idx=1&sn=4e1717e8becde11dfc15ac975af85748&source=41#wechat_redirect
代码参考
森林火灾:https://blog.csdn.net/qq_43585318/article/details/104261827
森林林火灾&传染病:https://blog.csdn.net/weixin_42663919/article/details/104383758
传染病模拟:https://blog.csdn.net/qq_43585318/article/details/104261827
除此之外还可以用于城市发展扩张,交通状况模拟,博物馆逃生模拟(美赛19D)等问题
待更