1

我将数据作为具有多个层的结构,例如:
data.A.B
我要访问的数据在 layer 中B。但问题是,B根据数据的来源,字段名称可能会有所不同。因此我不能只输入:
data.A.B.myData
myDatais 本身struct

我可以使用:
fieldnames(data.A)
来查找名称,但这对我没有多大帮助。我必须为可能出现在此级别的每个可能的字段名称编写代码部分。这正是我试图避免的。

有没有办法在myData不知道字段名称的情况下获取我拥有的数据()B

4

2 回答 2

1

You just need a recursive function that checks fieldnames at each level for the structure. This is roughly what you need (it could be improved to supply the path to the found field).

function [ value, found ] = FindField( rootStruct, fieldName )
%FindField - Find a field with a structure
    value = [];
    found = 0;
    if isstruct( rootStruct )
        fields = fieldnames(rootStruct);
        for fi=1:length(fields)
            if strcmp(fields{fi}, fieldName )
                value = rootStruct.(fieldName);
                found = true;
                return;
            end
            [value, found ] = FindField( rootStruct.(fields{fi}), fieldName );
            if found
                return;
            end
        end
    end

end

Usage example:

a.b = 1;
a.b.c = 2;
a.b.d = struct('Index',1,'Special',2);
FindField(a,'d')


ans = 

      Index: 1
    Special: 2
于 2013-11-15T03:27:19.663 回答
1

Traditionally, you can loop over the fieldnames and perform the search of myData at a specific sub-structure of the struct. However, if you don't know which sub-structure you need to search, then you can perform a recursive algorithm. Below is an example. It will return the first match of myData in the struct or an empty matrix if no match found. The code can be improved to find all matches of myData.

function S2=getmyfield(S1,queriedField)

if isstruct(S1)
    % Get all fieldnames of S1
    fieldArray=fieldnames(S1);

    % Find any match with the queried field. You can also use isfield().
    % If there is a match return the value of S1.(queriedField),
    % else perform a loop and recurse this function.
    matchTF=strcmp(queriedField,fieldArray);
    if any(matchTF)
        S2=S1.(fieldArray{matchTF});
        return;
    else
        S2=[];
        i=0; % an iterator count
        while isempty(S2)
            i=i+1;
            S2=getmyfield(S1.(fieldArray{i}),queriedField);
        end
    end
else
    S2=[];
end

end

Cheers.

于 2013-11-15T03:29:27.960 回答