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

标签 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.

还有其他想法吗?

最佳答案

使用

[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/

相关文章:

matlab - 如果我之前已经添加了填充,如何返回图像的尺寸?在Matlab中

c++ - 如何在 mex 代码中表示 MATLAB 的二维数组

c - For 循环不以空终止符终止

javascript - 从对象映射中获取键名称

javascript - 如何将一个数组值链接到另一个数组值?

matlab - 查找特定 matlab 工具箱中使用的函数

javascript - 当对象非常多并且我试图在范围内访问它时,为什么我会得到 "Can not read property 0 of undefined"?

arrays - 如何将数组转换为元组?

matlab - max 会引入舍入误差吗?

matlab - 在左轴上绘制折线图,​​在右轴上绘制条形图