matlab 结构体

在前面,有用到一个cell2struct()函数,cell是单元数组,而struct就是结构体。
1.建立结构体,在matlab中建立结构体有两种方式,
eg:第一种为直接赋值

>> stu(1).name='zhangsan';
>> stu(1).age=28;
>> stu(1).gender='male';
>> stu(2).name='lisi';
>> stu(2).age=29;
>>stu(2).gender='male';
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

第二种为用函数struct()
这里写图片描述

2.删除结构体操作rmfield()
s2=rmfield(s1,’color’)%删除s1中的一个字段color
s2=rmfield(s1,{‘color’,‘type’})%删除s1中的2个字段color和type

3.isstruct(s2)-判断是否为结构体

4.isfield(s2,’a’)-判断’a’字段是否属于这个结构体
b=isfield(s,{‘type’,’color’})-同时判断两个字段是否属于结构体,返回值就是两个数。

  1. fieldnames(s)-获取s结构体中的字段名字
    这里写图片描述

6.orderfields(s)-对s结构体中的字段进行排序,按首字母顺序

7.getfield()-取得结构体字段的值

8.setfield()-对结构体的字段赋予新的值

9.struct2cell(s)-将结构体s转换为单元数组

下面代码就是上面函数调用

clear all;
s1=struct('type',{'big','little'},'color',{'red'},'data',{[1 2 3;3 4 5]})
f1= getfield(s1,{1,2},'type')
f2= getfield(s1,{1,1},'type')
s2=setfield(s1,{1,2},'data',[7 7 7])
getfield(s2,{1,2},'data')
    
    
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

结果截图
这里写图片描述
这里写图片描述

                                            <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/production/markdown_views-ea0013b516.css">
                                </div>

在前面,有用到一个cell2struct()函数,cell是单元数组,而struct就是结构体。
1.建立结构体,在matlab中建立结构体有两种方式,
eg:第一种为直接赋值

>> stu(1).name='zhangsan';
>> stu(1).age=28;
>> stu(1).gender='male';
>> stu(2).name='lisi';
>> stu(2).age=29;
>>stu(2).gender='male';
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

第二种为用函数struct()
这里写图片描述

2.删除结构体操作rmfield()
s2=rmfield(s1,’color’)%删除s1中的一个字段color
s2=rmfield(s1,{‘color’,‘type’})%删除s1中的2个字段color和type

3.isstruct(s2)-判断是否为结构体

4.isfield(s2,’a’)-判断’a’字段是否属于这个结构体
b=isfield(s,{‘type’,’color’})-同时判断两个字段是否属于结构体,返回值就是两个数。

  1. fieldnames(s)-获取s结构体中的字段名字
    这里写图片描述

6.orderfields(s)-对s结构体中的字段进行排序,按首字母顺序

7.getfield()-取得结构体字段的值

8.setfield()-对结构体的字段赋予新的值

9.struct2cell(s)-将结构体s转换为单元数组

下面代码就是上面函数调用

clear all;
s1=struct('type',{'big','little'},'color',{'red'},'data',{[1 2 3;3 4 5]})
f1= getfield(s1,{1,2},'type')
f2= getfield(s1,{1,1},'type')
s2=setfield(s1,{1,2},'data',[7 7 7])
getfield(s2,{1,2},'data')
  
  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

结果截图
这里写图片描述
这里写图片描述

                                            <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/production/markdown_views-ea0013b516.css">
                                </div>

猜你喜欢

转载自blog.csdn.net/peiwang245/article/details/80081834