当字段名称未知时访问结构中的数据

时间:2013-11-15 02:53:14

标签: matlab matlab-struct

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

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

有没有办法在不知道myData的字段名称的情况下了解我的数据(B)?

2 个答案:

答案 0 :(得分:1)

您只需要一个递归函数来检查结构的每个级别的字段名称。 这大致是您所需要的(可以改进它以提供找到的字段的路径)。

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

用法示例:

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


ans = 

      Index: 1
    Special: 2

答案 1 :(得分:1)

传统上,您可以遍历fieldnames并在结构的特定子结构上搜索myData。但是,如果您不知道需要搜索哪个子结构,则可以执行递归算法。以下是一个例子。如果找不到匹配项,它将返回结构中myData的第一个匹配项或空矩阵。可以改进代码以查找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

干杯。