access to struct fields based on struct name

前端 未结 1 1054
悲&欢浪女
悲&欢浪女 2021-01-16 04:26

I have problem to access each field of struct in MATLAB. I tried to convert it to Cell however, it give me error :( How can I access each field with 2 loops ? I have wrote

1条回答
  •  孤街浪徒
    2021-01-16 04:59

    You can access a structure dynamically with s.(fname) where fname is char variable. Note the ( ) around fname.

    An example will clarify:

    % Example structure
    s.A = 10;
    s.B = 20;
    
    % Retrieve fieldnames
    fnames = fieldnames(s);
    
    % Loop with numeric index
    for ii = 1:numel(fnames)
        s.(fnames{ii})
    end
    
    % ...or loop by fieldname directly
    for f = fnames'
        s.(f{:})
    end
    

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题