MATLAB编程实践12、13

这篇具有很好参考价值的文章主要介绍了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);

MATLAB编程实践12、13,matlab

MATLAB编程实践12、13,matlab

循环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);

MATLAB编程实践12、13,matlab

 MATLAB编程实践12、13,matlab

MATLAB编程实践12、13,matlab


 曼德勃罗集


曼德勃罗集是一个包含z0值的复平面区域,其轨迹定义为MATLAB编程实践12、13,matlab

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)))  

MATLAB编程实践12、13,matlab文章来源地址https://www.toymoban.com/news/detail-620035.html

到了这里,关于MATLAB编程实践12、13的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • matlab 13折线法数据量化编码与解码

    模拟信号抽样后变成时间离散的信号,经过量化后,此抽样信号才能成为数字信号。分析可知:最简单的均匀量化器对于小输入信号很不利。为了改善小信号时的信号量噪比,在实际应用中常采用非均匀量化。 非均匀量化时,量化间隔随信号抽样值的不同而变化。信号抽样值

    2024年02月09日
    浏览(40)
  • matlab使用教程(13)—稀疏矩阵创建和使用

            使用稀疏矩阵存储包含众多零值元素的数据,可以节省大量内存并加快该数据的处理速度。 sparse 是一种属性,可以将该属性分配给由 double 或 logical 元素组成的任何二维 MATLAB 矩阵。通过 sparse 属性,MATLAB 可以:         • 仅存储矩阵中的非零元素及其索引。

    2024年02月13日
    浏览(29)
  • C Primer Plus(第六版)11.13 编程练习 第12题

    /* 编写一个程序,读取输入,直至读到EOF,报告读入的单词数、大写字母数、小写字母数、标点 符号数和数字字符数。使用ctype.h头文件中的函数。 */ //测试字符串  //ajskm,dl kdAj,.lfj sjkdl  sdk12lfj !.,fkdj.,.lssd.1a //(ajskm),(dl) (kdAj),.(lfj) (sjkdl)  (sdk)12(lfj) !.,(fkdj).,.(lssd).1(a) #includestdi

    2024年02月02日
    浏览(34)
  • matlab appdesigner系列-常用12-日期选择器

    日期选择器 ,目的就是显示时间,时间格式目前常用的 正序2024/1/19    也有倒序 19/1/2024 或者写成年-月-日格式的, 此示例,为当用户要更改日期时,弹出对话框提示:把日期从XXX改到XXX?确认日期更改 如果用户取消修改,则回到之前的日期。 用到的语句有: event相关的属

    2024年01月21日
    浏览(30)
  • Matlab进阶绘图第12期—局部放大图

    最近资源群里有好几个朋友问我该 如何对一幅图上的局部区域进行放大展示,从而可以更好地描绘细节信息 …… 于是,便有了本期内容。 局部放大图的绘制方法有很多,但为了使用方便, 本文直接利用BaseZoom工具(Kepeng Qiu.  Matlab Central,  2022)进行局部放大图的绘制 ,先来看

    2024年02月06日
    浏览(38)
  • 蓝桥杯青少年创意编程 C++组 国赛(第11届、第12届、第13届)

    蓝桥杯青少年组第十一届C++全国赛高级组讲解视频 蓝桥杯青少年组第十一届C++全国赛高级组讲解视频_哔哩哔哩_bilibili 蓝桥杯青少年组第十一届C++全国赛高级组讲解视频 蓝桥杯青少年组第十一届C++全国赛高级组讲解视频_哔哩哔哩_bilibili 蓝桥杯青少组C++省赛2020届真题讲解 蓝

    2024年02月06日
    浏览(42)
  • Matlab并行计算实践

    需要对上万张图像进行OCR识别。OCR算法原型用Matlab脚本实现,对每张图逐行逐字符识别,整体计算时间很长。找多核多CPU并行执行的方案 Matlab有并行工具箱。可以使用parfor对循环进行并行处理,parfor要求循环之间的运算独立不相关;另一种方式用SPMD模式,类似多线程/多进程方式

    2024年01月16日
    浏览(27)
  • MATLAB :【12】手把手教你在Linux以命令行方式(静默方式/非图形化方式)安装MATLAB(正版)

    碎碎念: (我知道我已经鸽了两个月,但是已经攒了很多的稿子没有发) 大家好,由于实验室的服务器中没有提供MATLAB的计算资源( 事实证明是我不知道QAQ ),在Ubuntu中安装了非图形的MATLAB。 通过参考其他博主的思路,并且利用T大提供的正版资源,中间踩了不少坑,最终

    2024年02月09日
    浏览(33)
  • 开源代码分享(12)—考虑负荷曲线的配电网扩展规划(附matlab代码)

            电力系统(SEP)不断扩展,以满足电力消费者的需求。在这个背景下,配电系统扩展规划(PESD)确定了配电网络扩展的指导方针。除了SEP的扩展之外,现代化和新技术的出现,例如分布式发电(GD)装置,都会影响电力系统,进而影响配电网络的质量和可靠性[1

    2024年02月14日
    浏览(31)
  • 【MATLAB数据处理实用案例详解(13)】——利用Elman网络实现上证股市开盘价预测

    选择2005年6月30日至2006年12月1日的上证开盘价进行预测分析。数据保存在elm_stock.mat文件中,共计337条开盘价格,保存为double类型的向量中,开盘价的走势如下图所示。 采用过去的股价预测下一期股价,因此相当于一个时间序列问题,可以用Elman神经网络求解。 x n = f ( x n −

    2024年02月03日
    浏览(65)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包