MATLAB Answers

Create a nested structure using a variable as field name

98 views (last 30 days)
Luca Amerio
Luca Amerio on 3 Nov 2016
Commented: Luca Amerio on 3 Nov 2016
Hi everybody
Lets say that I have a variable
of which I don't know the number of levels and that I would like to use this path as "address" of a variable inside a structure, such that
Now, I know that I can use string variables to set or get structure fileds using a notation like
But this works with one level or, with a bit of string manipulation, if I know the number of levels I must call. I'm thinking at something like:
Can you think of any kind of trick so that I can write a function that adapt itself to the number of levels I pass it through the path variable?


Sign in to comment.

Accepted Answer

Jan on 3 Nov 2016
Edited: Jan on 3 Nov 2016
This is a job for the getfield and setfield commands:
PathStr = '\levelOne\levelTwo\levelThree'; % Do not shadow the PATH command
Fields = strsplit(PathStr,'\'); % Ignore initial blank field later
S = [];
S = setfield(S, Fields{2:end}, 1)
V = getfield(S, Fields{2:end})
Internally this calls subsassgn, which can be done directly also. I'd move this into a function, which ignores at least a leading separator automatically:
function S = SetPathField(S, PathStr, Value)
if length(PathStr) >= 1 && PathStr(1) == '\'
Fields = regexp(PathStr(2:end), '\', 'split');
Fields = regexp(PathStr, '\', 'split');
Types = cell(1, numel(Fields));
Types(:) = {'.'};
S = subsasgn(S, struct('type', Types, 'subs', Fields), Value);

  1 Comment

Luca Amerio
Luca Amerio on 3 Nov 2016
Didn't know these two functions. They are exactly what I was looking for. Thank you

Sign in to comment.

More Answers (0)

Sign in to answer this question.



Translated by