对子结构体和字段进行索引
为代码生成对子结构体和字段进行索引时,请遵循以下规范:
例如,以下 MATLAB® 代码使用圆点表示法对字段和子结构体进行索引:
... substruct1.a1 = 15.2; substruct1.a2 = int8([1 2;3 4]); mystruct = struct('ele1',20.5,'ele2',single(100), 'ele3',substruct1); substruct2 = mystruct; substruct2.ele3.a2 = 2*(substruct1.a2); ...
生成的代码通过按如下方式解析符号对此示例中结构体的元素进行索引:
圆点表示法 | 符号解析 |
---|---|
substruct1.a1 | 局部结构体 substruct1 的字段 a1 |
substruct2.ele3.a1 | 字段 ele3 (局部结构体 substruct2 的子结构体)的字段 a1 的值 |
substruct2.ele3.a2(1,1) | 字段 ele3 (局部结构体 substruct2 的子结构体)的字段 a2 的第 1 行第 1 列中的值 |
要引用结构体数组中字段的值,您必须对数组中感兴趣的结构体进行索引,然后使用圆点表示法单独引用该结构体的字段,如以下示例所示:
... y = X(1).a % Extracts the value of field a % of the first structure in array X ...
要引用数组中每个结构体的特定字段的所有值,请在 for
循环中使用此表示法,如以下示例所示:
... s.a = 0; s.b = 0; X = repmat(s,1,5); for i = 1:5 X(i).a = i; X(i).b = i+1; end
此示例使用 repmat
函数定义结构体数组,每个结构体都有两个字段 a
和 b
,如 s
所定义。有关详细信息,请参阅 为代码生成定义结构体数组。
不能使用动态名称引用结构体中的字段,动态名称会将字段表示为 MATLAB 在运行时计算的变量表达式(请参阅基于变量生成字段名称)。
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
选择网站
选择网站以获取翻译的可用内容,以及查看当地活动和优惠。根据您的位置,我们建议您选择:。
您也可以从以下列表中选择网站:
如何获得最佳网站性能
选择中国网站(中文或英文)以获得最佳网站性能。其他 MathWorks 国家/地区网站并未针对您所在位置的访问进行优化。
美洲
- América Latina (Español)
- Canada (English)
- United States (English)
欧洲
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)