Access complex matlab struct with function/string -
i have matlab struct several levels (e.g. a.b(j).c(i).d). write function gives me fields want. if struct has 1 level, easy:
function x = test(struct, label1) x = struct.(label1) end e.g. if have struct a.b b via: test('b'). however, not work subfields, if have struct a.b.c can't use test('b.c') access it.
is there way pass string full field name (with dots) function retrieve field? or there better way fields select through function arguments?
the goal? sure, useless function 1 fieldname, wan't pass list of fieldnames argument receive these fields.
you should use subsref function:
function x = test(strct, label1) f=regexp(label1, '\.', 'split'); f(2:2:2*end)=f; f(1:2:end)={'.'}; x=subsref(strct, substruct(f{:})); end to access a.b.c can use:
subsref(a, substruct('.', 'b', '.', 'c')); the test function first splits input using .as delimiter , creates cell array f every other element filled . , elements passed substruct arguments.
note if there arrays of structs involved first one. a.b(i).c(j).d passing b.c.d return a.b(1).c(1).d. see this question way should handled.
as side note, renamed input variable struct strct because struct built-in matlab command.
Comments
Post a Comment