MATLAB编程实践12、13

chatgpt/2023/9/26 13:38:10

生命游戏


        游戏的宇宙是无限可扩展的二维矩形网格,群体是那些标注为存活的网格的集合。群体可以依照称为的离散时间步距进化。在每一步中,每个网格的命运由它周围最近的8个网格邻居的活度决定,规则如下:

        如果一个存活的网格有两个(或三个)存活的邻居,或者一个死亡的网格周围有三个存活的邻居,则它在下一步中也是存活的。


滑翔机

        滑翔机五网格群体初始结构,每一步进化过程中,都有两个网格死亡,并有两个新网格出生。

访问周围网格,并计算存活数目

      n = size(X,1);p = [1 1:n-1];q = [2:n n];% Count how many of the eight neighbors are alive.Y = X(:,p) + X(:,q) + X(p,:) + X(q,:) + ...X(p,p) + X(q,q) + X(p,q) + X(q,p);% A live cell with two live neighbors, or any cell with% three live neigbhors, is alive at the next step.X = (X & (Y == 2)) | (Y == 3);[loop,buttons] = query_buttons(buttons,pop);t = t + 1;

产生随机的初始群体

% Generate a random initial populationX = sparse(50,50);X(21:30,21:30) = (rand(10,10) > .75);p0 = nnz(X);

循环100代

% Loop over 100 generations.for t = 1:100spy(X)title(num2str(t))drawnow% Whether cells stay alive, die, or generate new cells depends% upon how many of their eight possible neighbors are alive.% Index vectors increase or decrease the centered index by one.n = size(X,1);p = [1 1:n-1];q = [2:n n];% Count how many of the eight neighbors are alive.Y = X(:,p) + X(:,q) + X(p,:) + X(q,:) + ...X(p,p) + X(q,q) + X(p,q) + X(q,p);% A live cell with two live neighbors, or any cell with% three live neigbhors, is alive at the next step.X = (X & (Y == 2)) | (Y == 3);endp100 = nnz(X);fprintf('%5d %5d %8.3f\n',p0,p100,p100/p0)

循环 


function lifex(varargin)lex = open_lex('lexicon.txt');
pop = population(lex,varargin{:});repeat = true;
while repeat% Place the initial population in the universe, X.[lex,pop] = read_lexicon(lex,pop);X = populate(pop);[plothandle,buttons] = initial_plot(size(X),pop);title(pop.name)t = 0;loop = true;while loop% Expand the universe if necessary to avoid the boundary.X = expand(X,pop);% Update the plot.[i,j] = find(X);set(plothandle,'xdata',j,'ydata',i);caption(t,nnz(X))drawnow% Whether cells stay alive, die, or generate new cells depends% upon how many of their eight possible neighbors are alive.% Index vectors increase or decrease the centered index by one.n = size(X,1);p = [1 1:n-1];q = [2:n n];% Count how many of the eight neighbors are alive.Y = X(:,p) + X(:,q) + X(p,:) + X(q,:) + ...X(p,p) + X(q,q) + X(p,q) + X(q,p);% A live cell with two live neighbors, or any cell with% three live neigbhors, is alive at the next step.X = (X & (Y == 2)) | (Y == 3);[loop,buttons] = query_buttons(buttons,pop);t = t + 1;end[repeat,pop] = what_next(buttons,lex,pop);end
fclose(lex.fid);
set(buttons(1:6),'vis','off')
set(buttons(7),'value',0,'string','close','call','close(gcf)')% ------------------------function lex = open_lex(filename)
% lex = file_open(filename)
%    lex.fid = file identifier
%    lex.len = number of entries
%    lex.index = index of current entrylex.fid = fopen(filename);
if lex.fid < 3error(['Cannot open "' filename '"'])
end
% Count number of usable entries,
lex.index = 0;
lex.len = 0;
while ~feof(lex.fid)% Look for a line with two colons, ':name:'.line = fgetl(lex.fid);if sum(line == ':') >= 2% name = line(2:find(line(2:end) == ':',1));% Look for an empty line or a line starting with a tab.tab = char(9);task = [tab '*'];tdot = [tab '.'];while ~feof(lex.fid)line = fgetl(lex.fid);if isempty(line)breakelseif strncmp(line(1:2),task,2) || strncmp(line(1:2),tdot,2)lex.len = lex.len + 1;% fprintf('%d: %s\n',lex.len,name)breakendendend
end
frewind(lex.fid);% ------------------------function pop = population(varargin)
% pop = population(varargin)
%    pop.index = index within lexicon of population 
%    pop.name = name of population
%    pop.all = logical flag for slide show of populations
%    pop.b = border width, default = 20
%    pop.S = sparse matrix representation of populationlex = varargin{1};
pop.index = 0;
pop.name = ' ';
pop.all = false;
pop.b = 20;
pop.S = [];
if nargin < 2pop.index = ceil(rand*lex.len);
elseif ischar(varargin{2}) && isequal(varargin{2},'all')pop.all = true;pop.b = 10;
elseif ischar(varargin{2})pop.name = varargin{2};pop.index = -1;
elseif min(size(varargin{2})) > 1pop.S = sparse(varargin{2});pop.name = sprintf('my %d-by-%d matrix',size(pop.S));
elsepop.index = varargin{2};
end
if nargin == 3pop.b = varargin{3};
end% ------------------------function [lex,pop] = read_lexicon(lex,pop)
% [lex,pop] = read_lexicon(lex,pop)
%    Update lex and pop to new populationif pop.all || pop.index > lex.lenpop.index = mod(pop.index,lex.len)+1;
end
if pop.index < lex.indexfrewind(lex.fid)lex.index = 0;
end
while lex.index ~= pop.index% Look for a line with two colons, ':name:'.line = fgetl(lex.fid);if sum(line == ':') >= 2name = line(2:find(line(2:end) == ':',1));% Look for an empty line or a line starting with a tab.tab = char(9);task = [tab '*'];tdot = [tab '.'];while ~feof(lex.fid) && lex.index <= lex.lenline = fgetl(lex.fid);if isempty(line)breakelseif strncmp(line(1:2),task,2) || strncmp(line(1:2),tdot,2)lex.index = lex.index + 1;if lex.index == pop.index || ...strncmpi(name,pop.name,length(pop.name))pop.index = lex.index;if pop.allpop.name = [name ',  index = ' int2str(pop.index)];elsepop.name = name;end% Form sparse matrix by rows from '.' and '*'.S = sparse(0,0);m = 0;while ~isempty(line) && (line(1)==tab)row = sparse(line(2:end) == '*');m = m+1;n = length(row);S(m,n) = 0;S(m,1:n) = row;line = fgetl(lex.fid);endpop.S = S;elseif lex.index == lex.lenerror('Population name is not in lexicon.')endbreakendendend
end% ------------------------function [plothandle,buttons] = initial_plot(sizex,pop)
% [plothandle,buttons] = initial_plot(size(X),pop)
%    plothandle = handle to customized "spy" plot
%    buttons = array of handles to toggle buttonsclf
shg
m = max(sizex);
ms = max(10-ceil(m/10),2);
plothandle = plot(0,0,'o','markersize',ms,'markerfacecolor','blue');
set(gca,'xlim',[0.5 m+0.5],'ylim',[0.5 m+0.5],'ydir','rev', ...'xtick',[],'ytick',[],'plotboxaspectratio',[m+2 m+2 1])
buttons = zeros(7,1);
bstrings = {'step','slow','fast','redo','next','random','quit'};
for k = 1:7buttons(k) = uicontrol('style','toggle','units','normal', ...'position',[.10+.12*(k-1) .005 .10 .045],'string',bstrings{k});
end
set(buttons(1),'userdata',0);
if pop.all, set(buttons(1:6),'vis','off'), end% ------------------------function X = populate(pop)
% X = populate(pop);
%    X = sparse matrix universe with centered initial population[p,q] = size(pop.S);
n = max(p,q) + 2*pop.b;
X = sparse(n,n);
i = floor((n-p)/2)+(1:p);
j = floor((n-q)/2)+(1:q);
X(i,j) = pop.S;% ------------------------function X = expand(X,pop)
% X = expand(X);
% Expand size if necessary to keep zeros around the boundary. 
% Border width b avoids doing this every time step.
n = size(X,1);
b = max(pop.b,1);
if any(X(:,n-1) ~= 0) || any(X(n-1,:) ~= 0)X = [X sparse(n,b); sparse(b,n+b)];n = n + b;
end
if any(X(2,:) ~= 0) || any(X(:,2) ~= 0)X = [sparse(b,n+b); sparse(n,b) X];xlim = get(gca,'xlim')+b;ylim = get(gca,'ylim')+b;set(gca,'xlim',xlim,'ylim',ylim)
end% ------------------------function [loop,buttons] = query_buttons(buttons,pop)
% [loop,buttons] = query_buttons(buttons);
%    loop = true: continue time stepping
%    loop = false: restartif pop.allpause(1)loop = false;
elsebv = cell2mat(get(buttons,'value'));bk = get(buttons(1),'userdata');if bk == 0 || sum(bv==1) ~= 1while all(bv == 0)drawnowbv = cell2mat(get(buttons,'value'));endif sum(bv==1) > 1bv(bk) = 0;endbk = find(bv == 1);endset(buttons([1:bk-1 bk+1:7]),'value',0)switch bkcase 1  % stepset(buttons(1),'value',0);bk = 0;loop = true;case 2  % slowpause(.5)loop = true;case 3  % fastpause(.05)loop = true;otherwise, loop = false;end% Remember button numberset(buttons(1),'userdata',bk);
end% ------------------------function [repeat,pop] = what_next(buttons,lex,pop)
% [next,pop] = what_next(buttons,lex,pop);
%    repeat = true: start with a new population
%    repeat = false: exitbv = cell2mat(get(buttons,'value'));
bk = find(bv == 1);
set(buttons,'value',0)
repeat = true;
if ~isempty(bk)switch bkcase 4  % redopop.index = lex.index;case 5  % nextpop.index = mod(lex.index,lex.len)+1;case 6  % randompop.index = ceil(rand*lex.len);case 7  % quitrepeat = false;end
end% ------------------------function caption(t,nnz)
% caption(t,nnz(X))
% Print time step count and population size on the x-label.
s = sprintf('t=%3d, pop=%3d',t,nnz);
fs = get(0,'defaulttextfontsize')+2;
xlabel(s,'fontname','courier','fontsize',fs);

 


 曼德勃罗集


曼德勃罗集是一个包含z0值的复平面区域,其轨迹定义为z_{k+1}=z_{k}^2+z_{0}

z0=0.25-0.54i
z=0
z=z^2+z0

数组运算

%% Define the region.定义复平面域的分割方式x = 0: 0.05: 0.8;y = x';%% Create the two-dimensional complex grid using Tony's indexing trick.n = length(x);e = ones(n,1);z0 = x(e,:) + i*y(:,e);%% Or, do the same thing with meshgrid.[X,Y] = meshgrid(x,y);z0 = X + i*Y;%% Initialize the iterates and counts arrays.z = zeros(n,n);c = zeros(n,n);%% Here is the Mandelbrot iteration.depth = 32;for k = 1:depth  %循环次数z = z.^3 + z0;c(abs(z) < 2) = k;end%% Create an image from the counts.c  %直接显示矩阵cimage(c)axis image%% Colorscolormap(flipud(jet(depth)))  

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.exyb.cn/news/show-5314173.html

如若内容造成侵权/违法违规/事实不符,请联系郑州代理记账网进行投诉反馈,一经查实,立即删除!

相关文章

算法通关村第三关——不简单的数组增删改查

线性表基础 线性表概念 线性表就是具有相同特征数据元素的一个有限序列&#xff0c;其中包含元素的个数称为线性表的长度 线性表类型 从不同的角度看&#xff0c;线性表有不同的分类 语言实现角度 顺序表有两种实现方式 一体式 分离式 一体式结构 一体式&#xff1a;存储信息…

springboot通过接口执行本地shell脚本

首先创建springboot项目 shell脚本 #!/bin/shecho Hello World&#xff01;然后编写执行shell脚本的util类 import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List;pub…

【深度学习】【三维重建】windows11环境配置tiny-cuda-nn详细教程

【深度学习】【三维重建】windows11环境配置tiny-cuda-nn详细教程 文章目录 【深度学习】【三维重建】windows11环境配置tiny-cuda-nn详细教程前言确定版本对应关系源码编译安装tiny-cuda-nn总结 前言 本人windows11下使用【Instant Neural Surface Reconstruction】算法时需要…

C#文件操作从入门到精通(2)——查看某个dll中有哪些函数

kernel32.dll中含有ini文件操作使用的函数,我们可以通过VisualStudio自带的dumpbin.exe查看dll所包含的函数,操作步骤如下: 1、找到dumpbin.exe所在的文件夹 我的电脑中安装了VisualStudio2019社区版以及VisualStudio2017Professional,但是我发现VisualStudio2019社区版中…

ansible-playbook编写 lnmp 剧本

ansible-playbook编写 lnmp 剧本 vim /opt/lnmp/lnmp.yaml执行剧本 ansible-playbook lnmp.yaml

AR开发平台 | 探索AR技术在建筑设计中的创新应用与挑战

随着AR技术的不断发展和普及&#xff0c;越来越多的建筑师开始探索AR技术在建筑设计中的应用。AR(增强现实)技术可以通过将虚拟信息叠加到现实场景中&#xff0c;为设计师提供更加直观、真实的建筑可视化效果&#xff0c;同时也可以为用户带来更加沉浸式的体验。 AR开发平台广…

开发一个RISC-V上的操作系统(四)—— 内存管理

目录 往期文章传送门 一、内存管理简介 二、Linker Script 链接脚本 三、动态分配内存 四、测试 往期文章传送门 开发一个RISC-V上的操作系统&#xff08;一&#xff09;—— 环境搭建_riscv开发环境_Patarw_Li的博客-CSDN博客 开发一个RISC-V上的操作系统&#xff08;二…

JVM类加载器的作用和层次结构

类加载器的作用 1)通过一个类的全限定名来获取定义此类的二进制字节流。 2)将这个字节流所代表的静态存储结构转化为方法区的运行时数据结构。 3)在内存中生成一个代表这个类的java.lang.Class对象,这个对象存放在方法区中。这个对象将作为程序访问方法区中的这些数据的外部接…
推荐文章