在MATLAB中将值分配给结构数组的字段 [英] assigning values to a field of an structure array in MATLAB
问题描述
我想替换结构数组中字段的值.例如,在以下结构中,我想将所有1替换为3.
I want to replace the value of the fields in a structure array. For example, I want to replace all 1's with 3's in the following construction.
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循环.
Is there an easy syntax for this? I want to avoid ugly for loops for such simple operation.
推荐答案
Credits go to @Slayton, but you actually can do the same thing for assigning values too, using deal:
[a([a.b]==1).b]=deal(3)
那么细分:
[a.b]
检索数组a
的所有b
字段,并将其放入逗号分隔列表.
retrieves all b
fields of the array a
and puts this comma-separated-list in an array.
a([a.b]==1)
使用逻辑索引仅索引a
满足约束的元素.随后,上面的完整命令根据
uses logical indexing to index only the elements of a
that satisfy the constraint. Subsequently the full command above assigns the value 3
to all elements of the resulting comma-separated-list according to this.
这篇关于在MATLAB中将值分配给结构数组的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!