参考文献[1][2][3][4][5]
.1,.2,.3...
称为一个结构体的属性patient(3).name = 'New Name';
patient(3)
ans = struct with fields:
name: 'New Name'
billing: []
test: []
S(2) = load('mandrill.mat')
S 是一个 1×2 的数组。
S =
1×2 struct array with fields:
X
map
caption
对于非标量结构体,访问特定字段的语法为 structName(indices).fieldName。 重新显示 clown 图像,并指定 clown 结构体的索引 (1):
image(S(1).X)
colormap(S(1).map)
添加索引以选择并重新显示字段内容的左上角:
upperLeft = S(1).X(1:50,1:80);
image(upperLeft)
仅当引用结构体数组的 单个元素 时,才能为字段的部分内容建立索引。MATLAB® 不支持诸如 S(1:2).X(1:50,1:80) 的语句,后者尝试为结构体的多个元素的字段建立索引。
s.n.a = ones(3);
s.n.b = eye(4);
s.n.c = magic(5);
third_row_b = s.n.b(3,:)
变量 third_row_b 包含 eye(4) 的第三行。
third_row_b =
0 0 1 0
s(1).n(2).a = 2*ones(3);
s(1).n(2).b = 2*eye(4);
s(1).n(2).c = 2*magic(5);
s(2).n(1).a = '1a';
s(2).n(2).a = '2a';
s(2).n(1).b = '1b';
s(2).n(2).b = '2b';
s(2).n(1).c = '1c';
s(2).n(2).c = '2c';
结构体 s 现在包含下图中所示的数据。
在这里插入图片描述
part_two_eye = s(1).n(2).b(1:2,1:2)
这将返回 2*eye(4) 的左上角 2×2 的部分:
part_two_eye =
2 0
0 2
s(1).f = 1;
s(2).f = 'two';
s(3).f = 3 * ones(3);
s(1:3).f
或者 s.f
nums(1).f = 1;
nums(2).f = 2;
nums(3).f = 3;
allNums = [nums.f]
该代码返回
allNums =
1 2 3
numElements = arrayfun(@(x) numel(x.f), s)
语法 @(x) 可以创建匿名函数。此代码对数组 s 的每个元素调用 numel 函数,例如 numel(s(1).f),并返回
numElements =
1 3 9
[1]https://ww2.mathworks.cn/help/matlab/structures.html?searchHighlight=%E7%BB%93%E6%9E%84%E4%BD%93&s_tid=doc_srchtitle
[2]https://ww2.mathworks.cn/help/matlab/matlab_prog/create-a-structure-array.html
[3] https://ww2.mathworks.cn/help/matlab/matlab_prog/access-data-in-a-structure-array.html
[4] https://ww2.mathworks.cn/help/matlab/matlab_prog/access-data-in-nested-structures.html
[5]https://ww2.mathworks.cn/help/matlab/matlab_prog/access-multiple-elements-of-a-nonscalar-struct-array.html