如何在Matlab中复制结构域(非标量结构)?

时间:2018-05-21 21:50:15

标签: arrays matlab

假设我有非标量结构

res = struct(); res(1).name = 'hello'; res(2).name = 'world';

现在,我想将name字段的全部内容复制到另一个字段,例如tag

以下两项均无效:

>> res.tag = res.name;
Scalar structure required for this assignment.

>> [res.tag] = [res.name];
Insufficient number of outputs from right hand side of equal sign to satisfy assignment.

>> {res.tag} = {res.name};
 {res.tag} = {res.name};
           ↑
Error: The expression to the left of the equals sign is not a valid target for an assignment.

还有其他想法吗?

1 个答案:

答案 0 :(得分:6)

使用

[res(:).tag] = res(:).name;

或更简单地说,就像你发现自己一样:

[res.tag] = res.name;

左侧带方括号的语法类似于捕获函数返回的几个输出的语法:[out1, out2] = fun(...);见MATLAB special characters

实际上,语法res.tag生成comma-separated list;并且[...]为一个此类列表中的每个元素分配值的标准;见Assigning output from a comma-separated list

作业的右侧应该是另一个以逗号分隔的列表。如果它是单个元素,或者您想手动指定列表,则需要deal

values = {10, 20};
[res.test] = values{:}; % works. {:} produces a comma-separated list
[res.test] = 10,20; % doesn't work. Use `deal`
[res.test] = deal(10,20); % works
[res.test] = 10; % doesn't work, unless `res` is scalar. Use `deal`
[res.test] = deal(10); % also works. 10 is repeated as needed

您的尝试[res.tag] = [res.name];无效的原因是右侧的[res.name]将逗号分隔列表res.name的结果连接到 one < / em>数组,所以它与上面[res.test] = 10;的情况相同。