Create a nested structure using a variable as field name

조회 수: 14 (최근 30일)
Luca Amerio
Luca Amerio 2016년 11월 3일
댓글: Luca Amerio 2016년 11월 3일
Hi everybody
Lets say that I have a variable
path='\levelOne\levelTwo\levelThree'
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
S.levelOne.levelTwo.levelThree=1;
Now, I know that I can use string variables to set or get structure fileds using a notation like
fieldName='myField';
S.(fieldName)=1;
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:
path='\levelOne\levelTwo\levelThree'
fields=strsplit(path,'\');
[fieldOne,fieldTwo,fieldThree]=deal(fields{2:end});
S.(fieldOne).(fieldTwo).(fieldThree)=1;
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?

채택된 답변

Jan
Jan 2016년 11월 3일
편집: Jan 2016년 11월 3일
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');
else
Fields = regexp(PathStr, '\', 'split');
end
Types = cell(1, numel(Fields));
Types(:) = {'.'};
S = subsasgn(S, struct('type', Types, 'subs', Fields), Value);
end
  댓글 수: 1
Luca Amerio
Luca Amerio 2016년 11월 3일
Didn't know these two functions. They are exactly what I was looking for. Thank you

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Search Path에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by