Accessing data in structures without loops

独自空忆成欢 提交于 2019-12-12 19:46:34

问题


I have a set of strings vals, for example:

vals = {'AD', 'BC'}

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.

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

without success. I think arrayfun may be the appropriate way, but I can't figure out the right syntax.


回答1:


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

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);


来源:https://stackoverflow.com/questions/18000072/accessing-data-in-structures-without-loops

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!