Matlab中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 的结构体:snake算法
转换沿其第⼀个维度的 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'}