MATLAB基本操作(四):结构体struct&元胞数组cell

来源:互联网 发布:mac充电器怎么用 编辑:程序博客网 时间:2024/05/20 08:27
一,结构体的使用
      1)直接创建法:         
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. >> student.name='Tom';  
  2. >> student.age=20;  
  3. >> student.sex='male';  
  4. >> student  
  5. student =   
  6.     name: 'Tom'  
  7.      age: 20  
  8.      sex: 'male'  
       要创建多个呢?加上下标就行了~~~
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. >> student(1).name='Tom';  
  2. student(1).age=20;  
  3. student(1).sex='male';  
  4. >> student(2).name='rose';  
  5. student(2).age=21;  
  6. student(2).sex='female';  
  7. >> student  
  8. student =   
  9. 1x2 struct array with fields:  
  10.     name  
  11.     age  
  12.     sex  
  13. >> student(1)  
  14. ans =   
  15.     name: 'Tom'  
  16.      age: 20  
  17.      sex: 'male'  
  18. >> student(2)  
  19. ans =   
  20.     name: 'rose'  
  21.      age: 21  
  22.      sex: 'female'  
     2)用关键字struct创建
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. >> student=struct('name',{'Tom','rose'},'age',{20,21});  
  2. >> student  
  3. student =   
  4. 1x2 struct array with fields:  
  5.     name  
  6.     age  
  7. >> student(1)  
  8. ans =   
  9.     name: 'Tom'  
  10.      age: 20  
  11. >> student(2)  
  12. ans =   
  13.     name: 'rose'  
  14.      age: 21  

     3)要增加字段怎么办?直接在结构体名后加 .字段名
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. student(1).id=100;  
     4)要删除字段呢?使用函数rmfield(,)
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. student=rmfield(student,'id');  
     5)几个函数
            fieldnames(student); %返回字段名
            isfield(student,'age');
            isstruct(student);
            struct2cell(student);


二,元胞数组
      它与数组的区别是:每个元素可以是不同类型的,可是不同大小的矩阵,也可以是字符串,结构体等
      使用元胞数组要区分(),{}的区别。
     1)创建元胞数组
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. >> c(1,1)={[1,2;3 4]};  
  2. >> c(1,2)={'tom is a sb'};  
  3. >> c(2,1)={[1,2,3,4,5,6]};  
  4. >> c(2,2)={struct('name','rose','age',21)};  
  5. >> c  
  6. c =   
  7.     [2x2 double]    'tom is a sb'  
  8.     [1x6 double]     [1x1 struct]  
  9. >> c(1,1)  
  10. ans =   
  11.     [2x2 double]  
  12. >> c{1,1}  
  13. ans =  
  14.      1     2  
  15.      3     4  
  16. >>   

{ }:可以返回一个元胞中的具体数据;
() :返回该位置的数组类型信息
[cpp] view plaincopy在CODE上查看代码片派生到我的代码片
  1. >> B(3,3)={'hello'};  
  2. >> B  
  3. B =   
  4.      []     []         []  
  5.      []     []         []  
  6.      []     []    'hello'  
  7. >>   

创建一个3*3的元胞数组,并组在(3,3)位置的赋值

   2)几个函数
       celldisp(c);     %显示
       cell2struct();
       num2cell();
       iscell();


总结:1)struct和cell看起来是像相似的,其实可以这样理解struct只能过构造1*n个元素,而cell就是个变态版的数                     组;
           2)他们真的没什么联系~~~

0 0
原创粉丝点击