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 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.mzph.cn/news/17739.shtml

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

相关文章

dubbo-helloworld示例

1、工程架构 2、创建模块 &#xff08;1&#xff09;创建父工程,引入公共依赖 pom.xml依赖 <dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></depende…

图像处理库(Opencv, Matplotlib, PIL)以及三者之间的转换

文章目录 1. Opencv2. Matplotlib3. PIL4. 三者的区别和相互转换5. Torchvision 中的相关转换库5.1 ToPILImage([mode])5.2 ToTensor5.3 PILToTensor 1. Opencv opencv的基本图像类型可以和numpy数组相互转化&#xff0c;因此可以直接调用torch.from_numpy(img) 将图像转换成t…

SQL-事务

set autocommit 0; select * from acount where name 嘉宝 && acount.money > 1000; update acount set money money - 1000 where name 嘉宝; update acount set money money 1000 where name 煎包; commit ; 脏读;当有两个事务使用同一数据库时&#xff0c…

SQL SERVER使用发布订阅同步数据库遇到的坑

可能遇到的各种坑 1.在执行 xp_cmdshell 的过程中出错。调用 ‘CreateProcess’ 失败&#xff0c;错误代码: ‘5’ 网上有各种解决办法&#xff0c;包括改本地安全策略&#xff0c;将sql server服务的网络权限改为本机系统&#xff0c;改cmd用户的读写权限&#xff0c;退出360…

基于WSL2、Ubuntu和VS Code的CUDA平台运行C语言程序

一、CUDA程序执行方法 执行步骤为&#xff1a; 安装Visual Studio Code。在Visual Studio Code中安装插件WSL与电脑的WSL2进行连接。点击左下角&#xff0c;然后再选择连接到WSL。 在WSL中创建以 .cu 为后缀的文件。 rootDESKTOP-HR6VO5J:~# mkdir CUDA /…

【NLP-新工具】语音转文本与OpenAI的用途

一、说明 OpenAI最近2022发布了一个名为Whisper的新语音识别模型。与DALLE-2和GPT-3不同&#xff0c;Whisper是一个免费的开源模型。它的主要功能就是将语音翻译成文本。本文将介绍如何使用这个重要应用库。 二、 Whisper概念 2.1 Whisper是啥&#xff1f; Whisper 是一种自动…

Linux实战:五子棋

一、五子棋原理 采用二维数组保存棋盘信息,棋盘上面的任何一个位置,里面可以放置三类信息。 空用户1的落子(黑子)用户2的落子(白子)下棋就是在二维数组中找对应的空位置,进行落子落完子之后下来就要考虑该落子位置是否有”五子连珠“,进而进行输赢判定,每一次走棋,多…

selenium如何打开浏览器,等待用户输入完成后,再运行

selenium如何打开浏览器&#xff0c;等待用户输入完成后&#xff0c;再运行 一、在脚本中&#xff0c;等待用户输入 在使用 Selenium 打开浏览器后等待用户输入完成&#xff0c;可以使用 Python 编写一个简单的脚本来实现。首先&#xff0c;确保你已经安装了 Selenium 和对应的…

数据结构与算法

时间复杂度和空间复杂度 时间复杂度大 O 表示法&#xff1a;表示代码执行时间随这数据规模增大的变化趋势。 空间复杂度大 O 表示法&#xff1a;表示代码占用的存储空间随数据规模增大的变化趋势。 数组 编程语言中一般会有数组这种数据类型。不过&#xff0c;它不仅是编程…

【JAVASE】类与对象

⭐ 作者&#xff1a;小胡_不糊涂 &#x1f331; 作者主页&#xff1a;小胡_不糊涂的个人主页 &#x1f4c0; 收录专栏&#xff1a;浅谈Java &#x1f496; 持续更文&#xff0c;关注博主少走弯路&#xff0c;谢谢大家支持 &#x1f496; 类与对象 1. 面向对象1.1 什么是面向对象…

Cordova+Vue2.0打包apk,保姆教程来袭!

1.环境准备&#xff08;全部都需要配置环境变量&#xff09; java version "1.8.0_341" 安卓sdk android-29 Gradle 4.10.1 node v16.16.0 cordova 10.0.0 (cordova-lib10.1.0)2.安卓环境变量 1. 确认已安装 Android SDK Build-Tools 和 Android SDK Platform-Tool…

QMLDay2:圆角按钮,关联键盘左右键,鼠标点击。状态切换控制。

QMLDay2 test1 作用&#xff1a; 圆角按钮&#xff0c;关联键盘左右键&#xff0c;鼠标点击。状态切换控制。 代码&#xff1a; import QtQuick 2.15 import QtQuick.Window 2.15 import QtQuick.Controls 2.15Window {width: 640height: 480visible: truecolor: "wh…

mysql--InnoDB存储引擎--架构和事务

MySQL进阶篇 文章目录 架构1、逻辑结构InnoDB 逻辑存储单元主层级关系图&#xff1a;1、表空间2、段3、区4、页5、行总结&#xff1a; 2、架构2、1 内存架构2、2 磁盘架构 3、事务3、1事务基础&#xff08;1&#xff09;事务&#xff08;2&#xff09;特性 架构 1、逻辑结构 I…

IO进线程——库的制作(静态库、动态库)

库的制作 1、静态库 ①生成二进制文件 gcc -c linkstack.c -o linkstack.o②制作静态库文件&#xff0c;把.o文件转换为.a文件 ar crs liblinkstack.a linkstack.o③编译时链接 gcc linkstack_main.c -L. -llinkstack2、动态库 ①生成地址无关二进制文件 gcc -fPIC -c l…

实现 rollup 实现多模块打包

rollup 是一个 JavaScript 模块打包器&#xff0c;可以将许多 JavaScript 库和应用程序打包成少量的捆绑包&#xff0c;从而提高了应用程序的性能。本文详细描述如何通过 rollup 实现多模块打包。 前提 项目的目录结构 先看下项目的 package.json 文件夹&#xff1a; {&qu…

我的 365 天创作纪念日

✅作者简介&#xff1a;人工智能专业本科在读&#xff0c;喜欢计算机与编程&#xff0c;写博客记录自己的学习历程。 &#x1f34e;个人主页&#xff1a;小嗷犬的个人主页 &#x1f34a;个人网站&#xff1a;小嗷犬的技术小站 &#x1f96d;个人信条&#xff1a;为天地立心&…

【Unity造轮子】实现一个类csgo的武器轮盘功能

文章目录 前言素材导入开始1.放背景和中间的圆圈&#xff0c;调整合适的宽高和位置2.添加选择图像框3.添加一些武器道具选择4.书写脚本RadialMenuManager5.绑定脚本和对象6.运行效果&#xff0c;按tab键开启关闭轮盘7.优化添加显示选中的武器文本8.添加鼠标选中放大的效果9.添加…

MySQL和Oracle区别

由于SQL Server不常用&#xff0c;所以这里只针对MySQL数据库和Oracle数据库的区别 (1) 对事务的提交 MySQL默认是自动提交&#xff0c;而Oracle默认不自动提交&#xff0c;需要用户手动提交&#xff0c;需要在写commit;指令或者点击commit按钮 (2) 分页查询 MySQL是直接在SQL…

JIT 与 C#热更

JIT与AOT 一般程序运行有两种方式&#xff0c;静态编译与动态编译。 AOT: Ahead Of Time,预先&#xff08;静态&#xff09;编译 静态编译的程序&#xff0c;需要在执行之前全部翻译为机器码&#xff0c;运行前会使得程序安装时间相对较长&#xff0c;但程序运行的时候&#…

加载已训练好的目标检测YOLOv8,v5,v3,v6模型,对数据集中某张图片中的object打上方框、标出类别,并将图片保存到本地

参考的教程&#xff1a;Python - Ultralytics YOLOv8 Docs 在与ultralytics代码同一层级下新建 predict.py 里面写下面的内容。运行即可 from ultralytics import YOLO from PIL import Image import cv2# 加载计划使用的模型 model YOLO("yolov8n.pt") # load a…