假设我有非标量结构
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.
还有其他想法吗?
最佳答案
使用
[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]
side 将逗号分隔列表 res.name
的结果连接到 one 数组中,因此它与 [res.test] = 10;
以上。
关于arrays - 如何在 Matlab 中复制结构域(非标量结构)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50457044/