更新 Matlab 结构数组的每个元素中的一个字段 [英] Updating one field in every element of a Matlab struct array
问题描述
假设我有一个结构数组 arr
,其中每个元素都有一堆字段,包括一个名为 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
这显然有效,但我觉得应该有一种方法可以在一行代码中做到这一点(并且没有 for 循环).我想出的最好的是两行,并且需要一个临时变量:
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{:});
有什么想法吗?谢谢.
推荐答案
请注意,deal
在那里不是必需的:
Just a note, the deal
isn't necessary there:
[arr.val] = newVals{:}; % achieves the same as deal(newVals{:})
我知道如何做到这一点的唯一另一种方法(没有 foo 循环)是使用 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)
最后一个命令遍历 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
.
我认为这实际上比您之前的两行代码和 for 循环效率低,因为它返回 arr
的 copy 而不是就地操作.
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屋!