MATLAB编程实践12、13

news2025/1/21 1:04:13

生命游戏


        游戏的宇宙是无限可扩展的二维矩形网格,群体是那些标注为存活的网格的集合。群体可以依照称为的离散时间步距进化。在每一步中,每个网格的命运由它周围最近的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 population
   X = sparse(50,50);
   X(21:30,21:30) = (rand(10,10) > .75);
   p0 = nnz(X);

循环100代

% Loop over 100 generations.
   for t = 1:100
      
      spy(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);
   
   end
   
   p100 = 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 entry

lex.fid = fopen(filename);
if lex.fid < 3
   error(['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)
            break
         elseif strncmp(line(1:2),task,2) || strncmp(line(1:2),tdot,2)
            lex.len = lex.len + 1;
            % fprintf('%d: %s\n',lex.len,name)
            break
         end
      end
   end
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 population

lex = varargin{1};
pop.index = 0;
pop.name = ' ';
pop.all = false;
pop.b = 20;
pop.S = [];
if nargin < 2
   pop.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})) > 1
   pop.S = sparse(varargin{2});
   pop.name = sprintf('my %d-by-%d matrix',size(pop.S));
else
   pop.index = varargin{2};
end
if nargin == 3
   pop.b = varargin{3};
end

% ------------------------

function [lex,pop] = read_lexicon(lex,pop)
% [lex,pop] = read_lexicon(lex,pop)
%    Update lex and pop to new population

if pop.all || pop.index > lex.len
   pop.index = mod(pop.index,lex.len)+1;
end
if pop.index < lex.index
   frewind(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 == ':') >= 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) && lex.index <= lex.len
         line = fgetl(lex.fid);
         if isempty(line)
            break
         elseif 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.all
                  pop.name = [name ',  index = ' int2str(pop.index)];
               else
                  pop.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);
               end
               pop.S = S;
            elseif lex.index == lex.len
               error('Population name is not in lexicon.')
            end
            break
         end
      end
   end
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 buttons

clf
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:7
   buttons(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: restart

if pop.all
   pause(1)
   loop = false;
else
   bv = cell2mat(get(buttons,'value'));
   bk = get(buttons(1),'userdata');
   if bk == 0 || sum(bv==1) ~= 1
      while all(bv == 0)
         drawnow
         bv = cell2mat(get(buttons,'value'));
      end
      if sum(bv==1) > 1
         bv(bk) = 0;
      end
      bk = find(bv == 1);
   end
   set(buttons([1:bk-1 bk+1:7]),'value',0)
   switch bk
      case 1  % step
         set(buttons(1),'value',0);
         bk = 0;
         loop = true;
      case 2  % slow
         pause(.5)
         loop = true;
      case 3  % fast
         pause(.05)
         loop = true;
      otherwise, loop = false;
   end
   % Remember button number
   set(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: exit

bv = cell2mat(get(buttons,'value'));
bk = find(bv == 1);
set(buttons,'value',0)
repeat = true;
if ~isempty(bk)
   switch bk
      case 4  % redo
         pop.index = lex.index;
      case 5  % next
         pop.index = mod(lex.index,lex.len)+1;
      case 6  % random
         pop.index = ceil(rand*lex.len);
      case 7  % quit
         repeat = 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  %直接显示矩阵c
   image(c)
   axis image

%% Colors
   colormap(flipud(jet(depth)))  

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

想阻止BOT攻击?一起聚焦灵活有效的F5解决方案

伴随着突如其来的数字创新&#xff0c;使潜在的欺诈无处不在。现在&#xff0c;帮我们查找机票交易、位置理想的演唱会座位的 BOT技术正在为网络犯罪分子所利用。权威数据表示&#xff0c;在过去5年&#xff0c;撞库攻击已成为造成经济损失的最大原因之一&#xff0c;几乎每个企…

小研究 - 基于解析树的 Java Web 灰盒模糊测试(二)

由于 Java Web 应用业务场景复杂, 且对输入数据的结构有效性要求较高, 现有的测试方法和工具在测试Java Web 时存在测试用例的有效率较低的问题. 为了解决上述问题, 本文提出了基于解析树的 Java Web 应用灰盒模糊测试方法. 首先为 Java Web 应用程序的输入数据包进行语法建模创…

前端技术周刊 2023-07-30:Promise.withResolvers 进入 Stage3

项目地址&#xff1a;olivewind/weekly[1] 微信公众号&#xff1a;依赖注入 发布时间&#xff1a;2023.07.30 本周内容&#xff1a;资讯x2、开源x8、文章x4 动态 Promise.withResolvers 进入 Stage3 某些情况下需要在 Promise 外部获取 resolve 和 reject 句柄&#xff0c;我们…

【云原生】一文学会Docker存储所有特性

目录 1.Volumes 1.Volumes使用场景 2.持久将资源存放 3. 只读挂载 2.Bind mount Bind mounts使用场景 3.tmpfs mounts使用场景 4.Bind mounts和Volumes行为上的差异 5.docker file将存储内置到镜像中 6.volumes管理 1.查看存储卷 2.删除存储卷 3.查看存储卷的详细信息…

RWEQ模型参量提取

土壤风蚀是一个全球性的环境问题。中国是世界上受土壤风蚀危害最严重的国家之一&#xff0c;土壤风蚀是中国干旱、半干旱及部分湿润地区土地荒漠化的首要过程。中国风蚀荒漠化面积达160.74104km2&#xff0c;占国土总面积的16.7%&#xff0c;严重影响这些地区的资源开发和社会经…

机器学习深度学习——Dropout

&#x1f468;‍&#x1f393;作者简介&#xff1a;一位即将上大四&#xff0c;正专攻机器学习的保研er &#x1f30c;上期文章&#xff1a;机器学习&&深度学习——权重衰减 &#x1f4da;订阅专栏&#xff1a;机器学习&&深度学习 希望文章对你们有所帮助 Drop…

【MTI 6.S081 Lab】traps

【MTI 6.S081 Lab】traps RISC-V assembly (easy)Backtrace (moderate)实验任务Hints解决方案backtracesys_sleep Alarm (hard)实验任务test0: invoke handlerHint test1()/test2()/test3(): resume interrupted codeHints 解决方案trap.c中的时钟中断处理程序sys_sigalarmsys_…

大促之前全链路压测监控

1. skywalking服务监控 1.1 skywalking简介 Skywalking 是一个APM系统&#xff0c;即应用性能监控系统&#xff0c;为微服务架构和云原生架构系统设计 它通过探针自动收集所需的指标&#xff0c;并进行分布式追踪&#xff0c;通过这些调用链路以及指标&#xff0c;Skywalking …

使用Postman如何在接口测试前将请求的参数进行自定义处理

1、前言 当我们使用 Postman 进行接口测试时&#xff0c;对于简单的不需要处理的接口&#xff0c;直接请求即可&#xff0c;但是对于需要处理的接口&#xff0c;如需要转码、替换值等&#xff0c;则就麻烦一些&#xff0c;一般我们都是先手动把修改好的值拷贝到请求里再进行请…

计算机的大小端模式

计算机的大小端模式 大端/小端字节序字节序转换函数判断Linux字节序的方法string有字节序的说法吗64位系统和32位系统的区别 大端/小端字节序 计算机硬件有两种储存数据的方式&#xff1a;大端字节序&#xff08;big endian&#xff09;和小端字节序&#xff08;little endian…

MySQL数据库——DQL操作——基本查询

文章目录 前言事前准备——测试数据整表查询指定列查找别名查询MySQL运算符条件查询模糊查询排序查询聚合查询分组查询分组之后的条件筛选 分页查询将整张表的数据插入到另一张表中 前言 MySQL数据库常见的操作是增删查改&#xff0c;而其中数据的查询是使用最多&#xff0c;也…

玩转LaTeX(三)【数学公式(基础)、​矩阵、多行公式】

数学公式基础 导言区&#xff08;引包&#xff09; \usepackage{amsmath} %带星号的eqution 正文区 \begin{document}%数学公式初步 \section{简介} \LaTeX{}将排版内容分为文本模式和数学模式。文本模式用于普通文本排版&#xff0c;数学模式用于数学公式排版。 …

小白带你学习linux的mysql服务(主从mysql服务和读写分离三十一)

目录 二、MySQL Replication优点&#xff1a; 三、MySQL复制类型 1、异步复制&#xff08;Asynchronous repication&#xff09; 2、全同步复制&#xff08;Fully synchronous replication&#xff09; 3、半同步复制&#xff08;Semisynchronous replication&#xff09;…

用pip给python安装第三方包

2023年7月30日&#xff0c;周日晚上 目录 搜索包安装包升级包卸载包查看安装了哪些包查看指定的包的详细信息查看pip把某个包安装到了哪里 搜索包 现在只能去专门的网站搜索python的第三方包了 Search results PyPI 安装包 通过下面这条指令就可以安装包 pip install pac…

【数据分享】1999—2021年地级市工业企业资产情况和主要财务指标(Excel/Shp格式)

在之前的文章中&#xff0c;我们分享过基于2000-2022年《中国城市统计年鉴》整理的1999-2021年地级市的人口相关数据、各类用地面积数据、污染物排放和环境治理相关数据、房地产投资情况和商品房销售面积、社会消费品零售总额和年末金融机构存贷款余额、地方一般公共预算收支状…

Prometheus中的关键设计

1、标准先行&#xff0c;注重生态 Prometheus 最重要的规范就是指标命名方式&#xff0c;数据格式简单易读。比如&#xff0c;对于应用层面的监控&#xff0c;可以要求必须具备这几个信息。 指标名称 metric Prometheus 内置建立的规范就是叫 metric&#xff08;即 __name__…

RedLock + Redisson

目录 2.9 RedLock2.9.1 上述实现的分布式锁在集群状态下失效的原因2.9.2 解决方式-RedLock 2.10 redisson中的分布式锁简单使用redisson中的锁Redisson常用配置2.10.1 Redisson可重入锁实现原理2.10.2 公平锁&#xff08;Fair Lock&#xff09; 2.9 RedLock 2.9.1 上述实现的分…

FLinkCDC读取MySQl时间戳时区相关问题解决汇总

FlinkCDC时间问题timestamp等https://blog.csdn.net/qq_30529079/article/details/127809317 FLinkCDC读取MySQl中的日期问题https://blog.csdn.net/YPeiQi/article/details/130265653 关于flink1.11 flink sql使用cdc时区差8小时问题https://blog.csdn.net/weixin_44762298/…

Redis以及Java使用Redis

一、Redis的安装 Redis是一个基于内存的 key-value 结构数据库。 基于内存存储&#xff0c;读写性能高 适合存储热点数据&#xff08;热点商品、资讯、新闻&#xff09; 企业应用广泛 官网&#xff1a;https://redis.io 中文网&#xff1a;https://www.redis.net.cn/ Redis…

vuejs源码阅读之代码生成器

代码生成器是模版编译的最后以后&#xff0c;它的作用是将AST转换成渲染函数中的内容&#xff0c;这个内容可以称为代码字符串。 代码字符串可以被包装在函数中执行&#xff0c;这个函数就是我们通常说的渲染函数。 渲染函数被执行之后&#xff0c;可以生成一份VNode&#xf…