一、结构数组的创建
结构数组是对某个对象,不同属性的数据,用一组数据来表示,称为结构数组。MATLAB有关结构数组的函数如下表:
结构数组的创建,可以采取直接赋值或用函数struct来创建。
例3-26
下表是几个学生的档案。数组名为student,试用结构数组来表示。
用直接赋值学生的标识ID为
>> student(1).ID=101; %student为数组名,ID为字段名,中间必须用句号隔开
>> student(2).ID=102;
>> student(3).ID=103;
>> student(4).ID=104;
用直接赋值学生的姓名name为
>> student(1).name='wang';
>> student(2).name='Chang';
>> student(3).name='Li';
>> student(4).name='Lu';
用直接赋值学生的年龄age为
>> student(1).age=21;
>> student(2).age=20;
>> student(3).age=19;
>> student(4).age=23;
用直接赋值学生的性别sex为
>> student(1).sex='F';
>> student(2).sex='M';
>> student(3).sex='F';
>> student(4).sex='M';
用直接赋值学生的成绩score为
>> student(1).score=88;
>> student(2).score=95;
>> student(3).score=79;
>> student(4).score=73;
>> struct(student)
ans =
包含以下字段的 1×4 struct 数组:
ID
name
age
sex
score
如果用结构数组函数struct创建,则书写格式为
array_name=struct(‘field1’,val1,‘field2’,val2,…)
式中,array_name为结构数组名,field为字段名,val为对应字段的值。
二、结构数组与单元数组的转换
结构数组与单元数组的转换函数为
也可以进行逆转换,函数为
s为结构数组名,c为单元数组名。
假如结构数组s是多维的,则转换后的单元数组大小为
例3-27
今有树的品种为白桦,树高为 28.5 的结构数组信息,将其转换成单元数组。
>> S=struct('category','tree','height',28.5,'name','brich') %创建结构数组
S =
包含以下字段的 struct:
category: 'tree'
height: 28.5000
name: 'brich'
>> C=struct2cell(S) %转换成单元数组
C =
3×1 cell 数组
'tree'
[28.5000]
'brich'
>> size(C) %转换后的单元数组大小
ans =
3 1
例3-28
将例3-26结构体数组student转换成单元数组C
>> C=struct2cell(student);
>> C=[C(:,1),C(:,2),C(:,3),C(:,4)] %显示单元数组
C =
5×4 cell 数组
[ 101] [ 102] [103] [104]
'wang' 'Chang' 'Li' 'Lu'
[ 21] [ 20] [ 19] [ 23]
'F' 'M' 'F' 'M'
[ 88] [ 95] [ 79] [ 73]
三、单元数组的数据处理
MATLAB的单元数组虽然有类似Excel的功能,但其分析统计功能不如 Excel。例如,求平均数不能直接用平均值函数 mean ,当使用时,要将单元数组中单元的数值转换成数值向量,随后进行数值计算。
例3-29
求例3-26中单元数组C的考分score的平均值。
>> s=0; %设初值
>> for i=1:4 %取i等于1:4的循环
s(i)=C{4,i}; %将数组C的第四行第i列的内容赋入数值数组s
end,s,mean(s) %显示s及s的平均值
s =
88 95 79 73
ans =
83.7500