
2.1.5 结构体类型
MATLAB中的结构体与C语言中的结构体类似,一个结构体可以通过字段存储多个不同类型的数据。因此,结构体相当于一个数据容器,把多个相关联的不同类型的数据封装在一个结构体对象中。
如图2-1所示,结构体Student中有4个字段:姓名字段Name中存储了一个字符串类型的数据;年级字段Grade中存储了一个浮点类型数值;科目字段Subject中存储了一个一维字符串数组;成绩字段Result中存储了一个一维数组。

图2-1 结构体Student的示意图
一个结构体中可以有多个字段,每个字段又可以存储不同类型的数据,通过这种方式就把多个不同类型的数据组织在一个结构体对象中了。
创建结构体对象的方法有两种,即可以直接通过赋值语句给结构体的字段赋值,也可以使用结构体创建函数struct。两种方法的具体操作步骤如下。
(1)通过字段赋值创建结构体。在对结构体的字段进行赋值时,赋值表达式的变量名使用“结构体名称.字段名称”的形式书写,对同一个结构体可以进行多个字段的赋值。
例2-13:通过字段赋值创建结构体。
在命令行窗口中输入:

输出结果:

在命令行窗口中输入:

输出结果:

在本例中,先通过对4个字段进行赋值,创建了结构体对象Student;然后用whos函数分析出Student是一个1×1的结构体数组。
○ 注意
在进行字段赋值操作时,对于没有明确赋值的字段,MATLAB默认赋值为空数组。通过圆括号索引进行字段赋值,还可以创建任意尺寸的结构体数组。需要注意的是,同一个结构体数组中的所有结构体对象具有相同的字段组合。
(2)利用struct函数创建结构体。
struct函数的语法形式为:

上述语句可以创建结构体对象StrArray,并将其n个字段分别赋值为var1,var2,…,varn。
例2-14:利用struct函数创建结构体。
在命令行窗口中输入:

输出结果:


在命令行窗口中输入:

输出结果:

在命令行窗口中输入:

输出结果:

在命令行窗口中输入:

输出结果:

在命令行窗口中输入:

输出结果:

在命令行窗口中输入:

输出结果:


在命令行窗口中输入:

输出结果:

在命令行窗口中输入:

输出结果:
