matlab-结构体struct

来源:互联网 发布:韦雪不做淘宝了 编辑:程序博客网 时间:2024/05/27 20:40

在前面,有用到一个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';

第二种为用函数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')

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

0 0