quazgar
quazgar

Reputation: 4632

Dynamical access to nested fields in Matlab

(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

Answers (2)

Oleg
Oleg

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

quazgar
quazgar

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

Related Questions