无循环访问结构中的数据 [英] 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
PS
在这里,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屋!