Matlab從入門到精通(四)
MatLab結構體變數的定義與使用
1、直接輸入法輸入結構體變數
>> student.test=[99 56 96 87 67 69 87 76 92];
>> student.name='Wu Qing';
>> student.weight=68;
>> student.height=1.72;
>> student.num=2003214091;
>> student.add='School of civil engneering.Tsinghua university';
>> student.tel='1381042679*';
2、使用struct函式生成結構型變數
>> truct_array=struct('d',{{'北京','上海'}},'strengths',[40000 1000])
truct_array =
d: {'北京' '上海'}
strengths: [40000 1000]
struct的更多用法可以輸入help struct檢視.
3、在結構體變數中新增變數
student(1).gender='Male'; %在student中新增gender和age這2項記錄
>> student(1).age=25;
>> student(2).gender='Female';
>> student(2).age=21;
>> student %查詢student的結構
注:陣列下標是從1開始的
4、從結構體中刪除成員變數
>> student(1).name = 'b';
>> student(1).age = 23;
>> student(2).name = 'b';
>> student(2).age = 23;
>>student
1x2 struct array with fields:
name
age
>>student=rmfield(student,'age');
>>student
1x2 struct array with fields:
Name
>>student(1)
a
5、呼叫成員函式
>>student.name
ans =
a
ans =
b
>>student(1).name
ans =
a
6、getefield和setfield函式的使用
getefield函式取得當前儲存在某個成員變數中的值 。setfield函式給某個成員變數插入新的值 。
>> getfield(student(1),'name')
a
>>student(1) = setfield(student(1),'name','cv')
>>student(1)
cv