我想替换结构数组中字段的值。例如,我想在以下结构中将所有 1 替换为 3。
a(1).b = 1;
a(2).b = 2;
a(3).b = 1;
a([a.b] == 1).b = 3; % This doesn't work and spits out:
% "Insufficient outputs from right hand side to satisfy comma separated
% list expansion on left hand side. Missing [] are the most likely cause."
有没有简单的语法?对于这种简单的操作,我想避免丑陋的 for 循环。
最佳答案
致谢@Slayton,但实际上您也可以使用 deal 为赋值做同样的事情。 :
[a([a.b]==1).b]=deal(3)
所以分割:
[a.b]
检索数组 a
的所有 b
字段并将此 comma-separated-list 放入在数组中。
a([a.b]==1)
使用逻辑索引仅索引满足约束条件的a
元素。随后,上面的完整命令根据 this 将值 3
分配给结果逗号分隔列表的所有元素。 .
关于matlab - 在 MATLAB 中为结构数组的字段赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13324942/