Dynamical access to nested fields in Matlab

前端 未结 2 827
小鲜肉
小鲜肉 2020-12-18 07:01

(How) Can I dynamically access nested fields in Matlab? I was thinking about a test case like this one:

a = struct;
a.foo.bar = [];

place = {\'foo\', \'bar\         


        
相关标签:
2条回答
  • 2020-12-18 07:48

    One solution I am not very happy with, mainly because it lacks the elegance of the .( ) dynamical field names syntax, is:

    getfield(a, place{:})
    
    0 讨论(0)
  • 2020-12-18 07:48

    Just for the sake of variation, you can use subsref():

    a.foo.bar = 'hi';
    place     = {'foo', 'bar'};
    
    % Build subs for referencing a structure and apply subsref
    typesub   = [repmat({'.'},1,numel(place)); place];
    
    subsref(a,substruct(typesub{:}))
    ans =
    hi
    

    Without any doubt, getfield() is way more readable and faster if you have to build typesub (otherwise speed comparisons are indiscernible for such a basic task).

    0 讨论(0)
提交回复
热议问题