目录
cell2struct函数是将元胞数组转换为结构体数组。
语法
structArray = cell2struct(cellArray, fields, dim)
说明
通过元胞数组
structArray
= cell2struct(cellArray
,fields
,dim
)cellArray
中包含的信息创建一个结构体数组structArray
。
fields参数指定结构体数组的字段名称。此参数是一个字符数组、字符向量元胞数组或字符串数组。
dim参数向 MATLAB® 指示创建结构体数组时要使用的元胞数组的轴。使用数值double指定dim。
要使用从元胞数组的 N
行中获取的字段创建一个结构体数组,在fields参数中指定N个字段名称,在dim参数中指定数字 1。要使用从元胞数组的M列中获取的字段创建一个结构体数组,请在fields参数中指定M个字段名称,在dim参数中指定数字2。
structArray
输出是具有N个字段的结构体数组,其中 N
等于fields输入参数中的字段数。生成的结构体中的字段数必须等于沿要转换的维度dim的元胞数。
示例
创建下表以用于此部分中的示例。表中列出了有关一个工程公司的员工的信息。按行读取该表将显示按部门列出的员工姓名。按列读取该表将显示每个员工已在该公司工作的年数。
5 年 | 10 年 | 15 年 | |
---|---|---|---|
开发 | Lee, Reed, Hill | Dean, Frye | Lane, Fox, King |
销售 | Howe, Burns | Kirby, Ford | Hall |
管理 | 价格 | Clark, Shea | Sims |
质量 | Bates, Gray | Nash | Kay, Chase |
文档 | Lloyd, Young | Ryan, Hart, Roy | Marsh |
输入以下命令以创建初始元胞数组 employees
:
devel = {
{'Lee','Reed','Hill'}, {'Dean','Frye'}, ...
{'Lane','Fox','King'}};
sales = {
{'Howe','Burns'}, {'Kirby','Ford'}, {'Hall'}};
mgmt = {
{'Price'}, {'Clark','Shea'}, {'Sims'}};
qual = {
{'Bates','Gray'}, {'Nash'}, {'Kay','Chase'}};
docu = {
{'Lloyd','Young'}, {'Ryan','Hart','Roy'}, {'Marsh'}};
employees = [devel; sales; mgmt; qual; docu]
employees =
{1x3 cell} {1x2 cell} {1x3 cell}
{1x2 cell} {1x2 cell} {1x1 cell}
{1x1 cell} {1x2 cell} {1x1 cell}
{1x2 cell} {1x1 cell} {1x2 cell}
{1x2 cell} {1x3 cell} {1x1 cell}
下面即是生成的元胞数组:
将元胞数组转换为沿维度 1 的结构体:
转换沿其第一个维度的 5×3 元胞数组以构造一个具有 5 个字段的 3×1 结构体。沿元胞数组的维度 1 的每一行将变为结构体数组中的一个字段:
遍历第一个维度(即垂直维度),包含 5 行,每行的标题如下:
rowHeadings = {'development', 'sales', 'management', ...
'quality', 'documentation'};
将元胞数组转换为与此维度相关的结构体数组 depts
:使用此面向行的结构体查找已在公司工作超过 10 年的开发员工的姓名:
将相同的元胞数组转换为沿维度 2 的结构体:
转换沿其第二个维度的 5×3 元胞数组以构造一个具有 3 个字段的 5×1 结构体。沿元胞数组的维度 2 的每一列将变为结构体数组中的一个字段:
沿第二个维度(或水平维度)遍历元胞数组。列标题将变为生成的结构体的字段:
colHeadings = {'fiveYears' 'tenYears' 'fifteenYears'};
years = cell2struct(employees, colHeadings, 2)
years =
5x1 struct array with fields:
fiveYears
tenYears
fifteenYears
使用列向结构体时,将显示已在公司工作至少 5 年的销售和文件部门的员工数。
[~, sales_5years, ~, ~, docu_5years] = years.fiveYears
sales_5years =
'Howe' 'Burns'
docu_5years =
'Lloyd' 'Young'
仅将元胞数组的一部分转换为结构体:
仅转换元胞数组的第一行和最后一行。这将生成一个具有 2 个字段的 3×1 结构体数组:
rowHeadings = {'development', 'documentation'};
depts = cell2struct(employees([1,5],:), rowHeadings, 1)
depts =
3x1 struct array with fields:
development
documentation
显示对于所有三个时间段属于这些部门的员工:
for k=1:3
depts(k,:)
end
ans =
development: {'Lee' 'Reed' 'Hill'}
documentation: {'Lloyd' 'Young'}
ans =
development: {'Dean' 'Frye'}
documentation: {'Ryan' 'Hart' 'Roy'}
ans =
development: {'Lane' 'Fox' 'King'}
documentation: {'Marsh'}