zoukankan      html  css  js  c++  java
  • matlab基本数据结构struct

    一起来学演化计算-matlab基本数据结构struct

    觉得有用的话,欢迎一起讨论相互学习~Follow Me

    参考文献
    http://blog.sina.com.cn/s/blog_468651400100c6c0.html

    结构数组struct

    • MATLAB提供了两种定义结构的方式:直接应用和使用struct函数

    使用直接引用方式定义结构

    • 与建立数值型数组一样,建立新struct对象不需要事先申明,可以直接引用,而且可以动态扩充。比如建立一个复数变量x
    x.real = 0; % 创建字段名为real,并为该字段赋值为0
    x.imag = 0 % 为x创建一个新的字段imag,并为该字段赋值为0
    x =
    real: 0
    imag: 0
    然后可以将其动态扩充为数组:
    x(2).real = 0; % 将x扩充为1×2的结构数组
    x(2).imag = 0;
    在任何需要的时候,也可以为数组动态扩充字段,如增加字段scale:
    x(1).scale = 0;
    这样,所有x都增加了一个scale字段,而x(1)之外的其他变量的scale字段为空:
    x(1) % 查看结构数组的第一个元素的各个字段的内容
    ans =
    real: 0
    imag: 0
    scale: 0
    x(2) % 查看结构数组的第二个元素的各个字段的内容,注意没有赋值的字段为空
    ans =
    real: 0
    imag: 0
    scale: []
    
    • 应该注意的是,x的real、imag、scale字段不一定是单个数据元素,它们可以是任意数据类型,可以是向量、数组、矩阵甚至是其他结构变量或元胞数组,而且不同字段之间其数据类型不需要相同。例如:
    clear x; x.real = [1 2 3 4 5]; x.imag = ones(10,10);
    
    • 数组中不同元素的同一字段的数据类型也不要求一样
    x(2).real = '123';
    x(2).imag = rand(5,1);
    
    • 甚至还可以通过引用数组字段来定义结构数据类型的某字段
    x(3).real = x(1); x(3).imag = 3; x(3)
    ans =
    real: [1x1 struct]
    imag: 3
    

    使用struct函数创建结构

    • 使用struct函数也可以创建结构,该函数产生或把其他形式的数据转换为结构数组。
    • struct的使用格式为:
      s = sturct('field1',values1,'field2',values2,…);
    • 该函数将生成一个具有指定字段名和相应数据的结构数组,其包含的数据values1、valuese2等必须为具有相同维数的数据,数据的存放位置与其结构位置一一对应的。对于struct的赋值用到了元胞数组。数组values1、values2等可以是元胞数组、标量元胞单元或者单个数值。每个values的数据被赋值给相应的field字段。
    • 当valuesx为元胞数组的时候,生成的结构数组的维数与元胞数组的维数相同。而在数据中不包含元胞的时候,得到的结构数组的维数是1×1的。
    s = struct('type',{'big','little'},'color',{'blue','red'},'x',{3,4})
    s =
    1x2 struct array with fields:
    type
    color
    x
    % 得到维数为1×2的结构数组s,包含了type、color和x共3个字段。这是因为在struct函数中{'big','little'}、{'blue','red'}和{3,4}都是1×2的元胞数组,可以看到两个数据成分分别为:
    s(1,1)
    ans =
    type: 'big'
    color: 'blue'
    x: 3
       s(1,2)
    ans =
    type: 'little'
    color: 'red'
    x: 4
    % 相应的,如果将struct函数写成下面的形式:
    s = struct('type',{'big';'little'},'color',{'blue';'red'},'x',{3;4})
    s =
    2x1 struct array with fields:
    type
    color
    x
    % 则会得到一个2×1的结构数组。
    
  • 相关阅读:
    LeetCode 461. Hamming Distance
    LeetCode 442. Find All Duplicates in an Array
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode Find the Difference
    LeetCode 415. Add Strings
    LeetCode 445. Add Two Numbers II
    LeetCode 438. Find All Anagrams in a String
    LeetCode 463. Island Perimeter
    LeetCode 362. Design Hit Counter
    LeetCode 359. Logger Rate Limiter
  • 原文地址:https://www.cnblogs.com/cloud-ken/p/11268543.html
Copyright © 2011-2022 走看看