1. 程式人生 > >MATLAB基本操作(四):結構體struct&元胞陣列cell

MATLAB基本操作(四):結構體struct&元胞陣列cell

>> student(1).name='Tom';
student(1).age=20;
student(1).sex='male';
>> student(2).name='rose';
student(2).age=21;
student(2).sex='female';
>> student
student = 
1x2 struct array with fields:
    name
    age
    sex
>> student(1)
ans = 
    name: 'Tom'
     age: 20
     sex: 'male'
>> student(2)
ans = 
    name: 'rose'
     age: 21
     sex: 'female'
     2)用關鍵字struct建立
>> student=struct('name',{'Tom','rose'},'age',{20,21});
>> student
student = 
1x2 struct array with fields:
    name
    age
>> student(1)
ans = 
    name: 'Tom'
     age: 20
>> student(2)
ans = 
    name: 'rose'
     age: 21

     3)要增加欄位怎麼辦?直接在結構體名後加 .欄位名
student(1).id=100;
     4)要刪除欄位呢?使用函式rmfield(,)
student=rmfield(student,'id');
     5)幾個函式             fieldnames(student); %返回欄位名             isfield(student,'age');             isstruct(student);             struct2cell(student);
二,元胞陣列
      它與陣列的區別是:每個元素可以是不同型別的,可是不同大小的矩陣,也可以是字串,結構體等       使用元胞陣列要區分(),{}的區別。
     1)建立元胞陣列
>> c(1,1)={[1,2;3 4]};
>> c(1,2)={'tom is a sb'};
>> c(2,1)={[1,2,3,4,5,6]};
>> c(2,2)={struct('name','rose','age',21)};
>> c
c = 
    [2x2 double]    'tom is a sb'
    [1x6 double]     [1x1 struct]
>> c(1,1)
ans = 
    [2x2 double]
>> c{1,1}
ans =
     1     2
     3     4
>> 

{ }:可以返回一個元胞中的具體資料; () :返回該位置的陣列型別資訊
>> B(3,3)={'hello'};
>> B
B = 
     []     []         []
     []     []         []
     []     []    'hello'
>> 

建立一個3*3的元胞陣列,並組在(3,3)位置的賦值

   2)幾個函式