MATLAB编程实践12、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.mfbz.cn/a/54372.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

环形链表 II(JS)

环形链表 II 题目 给定一个链表的头节点 head &#xff0c;返回链表开始入环的第一个节点。 如果链表无环&#xff0c;则返回 null。 如果链表中有某个节点&#xff0c;可以通过连续跟踪 next 指针再次到达&#xff0c;则链表中存在环。 为了表示给定链表中的环&#xff0c;…

单例模式(Singleton)

单例模式保证一个类仅有一个实例&#xff0c;并提供一个全局访问点来访问它&#xff0c;这个类称为单例类。可见&#xff0c;在实现单例模式时&#xff0c;除了保证一个类只能创建一个实例外&#xff0c;还需提供一个全局访问点。 Singleton is a creational design pattern t…

小区智能电动汽车充电桩如何收费盈利?

摘要&#xff1a;智能用电小区是国家电网为了研究智能电网智能用电的先进技术如何运用于居民区&#xff0c;提高人民的生活水平&#xff0c;提高电网智能化水平以及提升用电服务质量而进行的一项尝试。电动汽车作为智能用电小区建设的一个组成部分同样也逐渐被纳入发展规划&…

wireshark导出H264裸流

导出H264裸流 安装wireshark下载rtp_h264_extractor.lua脚本配置lua脚本重启wireshark筛选 安装wireshark 下载抓包工具&#xff1a;首先&#xff0c;您需要下载并安装一个网络抓包工具&#xff0c;例如Wireshark&#xff08;https://www.wireshark.org&#xff09;或tcpdump&…

26 用lsqnonlin求解最小二乘问题(matlab程序)

1.简述 函数语法 x lsqnonlin(fun,x0) 函数用于&#xff1a; 解决非线性最小二乘(非线性数据拟合)问题 解决非线性最小二乘曲线拟合问题的形式 变量x的约束上下限为ub和lb&#xff0c; x lsqnonlin(fun,x0)从x0点开始&#xff0c;找到fun中描述的函数的最小平方和。函数fu…

Linux操作系统(一):详解CPU

学习操作系统往往需要先学习CPU相关知识&#xff0c;然后再学习操作系统的结构&#xff0c;主要是因为操作系统是运行在 CPU 上的核心软件&#xff0c;它通过与 CPU 的交互来管理计算机的硬件资源&#xff0c;执行各种系统服务&#xff0c;并为用户和应用程序提供接口和功能。 …

心理测量平台目录遍历

你知道&#xff0c;幸福不仅仅是吃饱穿暖&#xff0c;而是勇敢的战胜困难。 漏洞描述 心理测量平台存在目录遍历漏洞&#xff0c;攻击者可利用该漏洞获取敏感信息。 漏洞复现 访问目录遍历漏洞路径&#xff1a; /admin/漏洞证明&#xff1a; 文笔生疏&#xff0c;措辞浅薄…

Prometheus中的关键设计

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

clickhouse查询缓存

为了实现最佳性能&#xff0c;数据库需要优化其内部数据存储和处理管道的每一步。但是数据库执行的最好的工作是根本没有完成的工作&#xff01;缓存是一种特别流行的技术&#xff0c;它通过存储早期计算的结果或远程数据来避免不必要的工作&#xff0c;而访问这些数据的成本往…

Redis以及Java使用Redis

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

微信小程序监测版本更新

在index.js里面 不放到app.js里面是因为有登录页面&#xff0c;在登录页面显示更新不太友好 onShow() {const updateManager wx.getUpdateManager()// 请求完新版本信息的回调updateManager.onCheckForUpdate(res > {if (res.hasUpdate) {// 新版本下载成功updateManage…

B076-项目实战--宠物上下架 展示 领养 收购订单

目录 上下架功能提供后台宠物列表实现 前台展示前台宠物列表和详情展示店铺展示 领养分析前台后端PetControllerPetServiceImpl 订单需求分析可能产生订单的模块订单模块额外功能 订单设计表设计流程设计 集成基础代码收购订单创建订单前端后端 上下架功能提供 后台宠物列表实…

解决AttributeError: ‘DataParallel‘ object has no attribute ‘xxxx‘

问题描述 训练模型时&#xff0c;分阶段训练&#xff0c;第二阶段加载第一阶段训练好的模型的参数&#xff0c;接着训练 第一阶段训练&#xff0c;含有代码 if (train_on_gpu):if torch.cuda.device_count() > 1:net nn.DataParallel(net)net net.to(device)第二阶段训练…

数据结构-链表结构-单向链表

链表结构 说到链表结构就不得不提起数据结构&#xff0c;什么是数据结构&#xff1f;就是用来组织和存储数据的某种结构。那么到底是某种结构呢&#xff1f; 数据结构分为&#xff1a; 线性结构 数组&#xff0c;链表&#xff0c;栈&#xff0c;队列 树形结构 二叉树&#x…

P1219 [USACO1.5] 八皇后 Checker Challenge

题目 思路 非常经典的dfs题&#xff0c;需要一点点的剪枝 剪枝①&#xff1a;行、列&#xff0c;对角线的标记 剪枝②&#xff1a;记录每个皇后位置 代码 #include<bits/stdc.h> using namespace std; const int maxn105; int a[maxn];int n,ans; bool vis1[maxn],vis…

解决:请求的资源[/xxx/]不可用 描述 源服务器未能找到目标资源的表示或者是不愿公开一个已经存在的资源表示。

1. 复现错误 今天启动jsp servlet项目&#xff0c;却报出如下错误&#xff1a; 2. 分析问题 报出该错误&#xff0c;一般是tomcat无法访问webapp下的文件&#xff0c;特采用如下方法解决问题。 检查涉及到jdk的版本号是否一致&#xff0c;我的是1.8的版本&#xff0c;所以&am…

AI革命:揭开微软无与伦比的AI技术面纱

来源&#xff1a;猛兽财经 作者&#xff1a;猛兽财经 2023年7月25日&#xff0c;全球科技行业的领导者之一微软(MSFT)公布了其2023财年第四季度的财报。 除了举世闻名的Windows操作系统&#xff0c;微软还通过笔记本电脑、个人电脑和服务器等产品改变了世界&#xff0c;该公司…

QMessageBox类

QMessageBox类 静态方法例子 静态方法 调用这一些静态成员函数&#xff0c;就可以得到模态提示框 枚举值为&#xff1a; 例子 头文件&#xff1a; #ifndef MAINWINDOW_H #define MAINWINDOW_H#include <QMainWindow> #include <QMessageBox>QT_BEGIN_NAMESPACE…

gorm基础

Gorm 官方文档&#xff1a;https://gorm.io/zh_CN/ 安装 go get -u github.com/jinzhu/gorm连接数据库 连接不同的数据库都需要导入对应数据的驱动程序&#xff0c;GORM已经贴心的为我们包装了一些驱动程序&#xff0c;只需要按如下方式导入需要的数据库驱动即可&#xff1…

Android Studio 关于BottomNavigationView 无法预览视图我的解决办法

一、前言&#xff1a;最近在尝试一步一步开发一个自己的软件&#xff0c;刚开始遇到的问题就是当我们引用 com.google.android.material.bottomnavigation.BottomNavigationView出现了无法预览视图的现象&#xff0c;我也在网上查了很多中解决方法&#xff0c;最后在执行了如下…
最新文章