在Matlab的结构数组的每个元素更新一个字段 [英] Updating one field in every element of a Matlab struct array
问题描述
假设我有一个结构阵列改编
,其中每个元素都有一堆领域,其中包括一个叫 VAL
。我想用一些恒定的量,像这样来增加每个元素的 VAL
字段:
Suppose I have a struct array arr
, where each element has a bunch of fields, including one called val
. I'd like to increment each element's val
field by some constant amount, like so:
for i = 1:length(arr)
arr(i).val = arr(i).val + 3;
end
这显然是工作,但我觉得应该有一个方式只有一行code要做到这一点(没有循环)。我拿出最好的是两行,需要一个临时变量:
This obviously works, but I feel there should be a way to do this in just one line of code (and no for loop). The best I've come up with is two lines and requires a temp variable:
newVals = num2cell([arr.val] + 3);
[arr.val] = deal(newVals{:});
任何想法?谢谢你。
Any ideas? Thanks.
推荐答案
刚一说明,在交易
是没有必要的有:
Just a note, the deal
isn't necessary there:
[arr.val] = newVals{:}; % achieves the same as deal(newVals{:})
我知道如何做到这一点(不福尔循环)的唯一其他方法是使用 arrayfun
来遍历数组中的每个结构:
The only other way I know how to do this (without the foor loop) is using arrayfun
to iterate over each struct in the array:
% make a struct array
arr = [ struct('val',0,'id',1), struct('val',0,'id',2), struct('val',0,'id',3) ]
% some attempts
[arr.val]=arr.val; % fine
[arr.val]=arr.val+3; % NOT fine :(
% works !
arr2 = arrayfun(@(s) setfield(s,'val',s.val+3),arr)
这是最后一个命令遍历在每个结构改编
,并返回一个新的,其中 s.val
已定到 s.val = 3
。
That last command loops over each struct in arr
and returns a new one where s.val
has been set to s.val=3
.
我觉得这其实是比你的previous两班轮效率较低,在for循环,但因为它返回的复制的的改编
,而不是就地操作。
I think this is actually less efficient than your previous two-liner and the for loop though, because it returns a copy of arr
as opposed to operating in-place.
(这是一个耻辱Matlab的不支持分层索引如 [arr.val] = num2cell([arr.val] +3){:}
)
(It's a shame Matlab doesn't support layered indexing like [arr.val]=num2cell([arr.val]+3){:}
).
这篇关于在Matlab的结构数组的每个元素更新一个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!