在没有循环的情况下访问结构中的数据 [英] Accessing data in structures without loops
问题描述
我有一组字符串vals
,例如:
I have a set of strings vals
, for example:
vals = {'AD', 'BC'}
我还有一个结构体 info
,其中嵌套在与数组 vals
中的元素相对应的字段中的结构体(即 'AD' 和 'BC' 在这个例子中),每个依次在名为 lastcontract
的字段中存储一个数字.
I also have a struct info
, inside of which are structs nested in fields corresponding to the elements in the array vals
(that would be 'AD' and 'BC' in this example), each in turn storing a number in a field named lastcontract
.
我可以使用 for
循环为每个 vals
提取 lastcontract
,如下所示:
I can use a for
loop to extract lastcontract
for each of the vals
like this:
for index = 1:length(vals)
info.(vals{index}).lastcontract
end
如果可能的话,我想找到一种没有循环的方法,但我运气不好.我试过了:
I'd like to find a way of doing this without a loop if at all possible, but I'm not having luck. I tried:
info.(vals{1:2}).lastcontract
没有成功.我认为 arrayfun
可能是合适的方式,但我不知道正确的语法.
without success. I think arrayfun
may be the appropriate way, but I can't figure out the right syntax.
推荐答案
这里实际上可以在没有显式循环的情况下进行管理(也不是 arrayfun
/cellfun
):
It is actually possible here to manage without an explicit loop (nor arrayfun
/cellfun
):
C = struct2cell(info); %// Convert to cell array
idx = ismember(fieldnames(info), vals); %// Find fields
C = [C{idx}]; %// Flatten to structure array
result = [C.lastcontract]; %// Extract values
附注cellfun
在这里比 arrayfun
更合适,因为您迭代 vals
(一个元胞数组).为了练习,这里有一个 cellfun
的解决方案:
P.S
cellfun
would be more appropriate here than arrayfun
, because you iterate vals
(a cell array). For the sake of practice, here's a solution with cellfun
:
result = cellfun(@(x)info.(x).lastcontract, vals);
这篇关于在没有循环的情况下访问结构中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!