问题
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.Scellfun 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