Reputation: 4632
(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'};
a.(place{:})
% instead of the following, which only works if know in advance
% how many elements 'place' has
a.(place{1}).(place{2})
Upvotes: 5
Views: 1593
Reputation: 10676
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).
Upvotes: 3
Reputation: 4632
One solution I am not very happy with, mainly because it lacks the elegance of the .( )
dynamical field names syntax, is:
getfield(a, place{:})
Upvotes: 6