O, I get it, A is an object, and setField like something you apply to this object. I'm not familiar with object oriented programming. Any change I might get this to work though?
Accessing various field names deep in a structure.
조회 수: 22 (최근 30일)
이전 댓글 표시
hi
Image I want to access fieldnames one, two, three, four in structure A.B.C.D.E.F and so on, with each possible letter containing fieldnames one, two, three four, e.g. A.B.C.one, A.B.C.two. In one iteration, I might wanna get A.B.C.one, but in the next A.B.C.D.one. I could of course make switch cases like: case condition, then go to A.B.C.D.one, case ..., but I would like to parse to common part of the fieldnames, e.g. 'B.C.D.E' to A. like this: A.('B.C.D.E').one. As such, ('B.C.D.E') could be easily replaced by e.g. ('B.C.') and my code would be less redundant. In a post by Loren, I found the answer below to solve my problem, posted by Brad Stiritz. However, I don't get this to work, when I try
A.B.C.D = 50; ans = A.getField('A.B.C.D')
I get
Reference to non-existent field 'getField'.
I tried ans = getField(A,'B.C.D') and ans = getField(A,'A.B.C.D'), but also got errors. Anyone who has a similar solution or can get this to work?
Thx!
I cite: " I wrote a class ‘FieldInterface’ to encapsulate arbitrary-depth struct fields, just as you’re talking about, so I can do things like:
————————————–
A.setField(‘A.B.C.D’,20); ans = A.getField(‘A.B.C.D’);
————————————–
The code snip below is the essence of method getField(). Note the reference to classdef constant ROOT_FIELD_NAME, which anchors the “dynamic” Fields.
————————————–
function outValue = getField(obj,varargin) … fieldSpecStr = varargin{1}; … try
% Construct near-complete field name (only lacking ‘obj.’), e.g. % ‘ROOT_FIELD_NAME.subStructName.fieldName’ fullFieldStr = [ obj.ROOT_FIELD_NAME '.' fieldSpecStr ];
% Get cell vector of sub-struct / field names within (fullFieldStr) cvFieldSplits = regexp(fullFieldStr,’\.’,'split’);
% Initialize (outValue): outValue = obj;
% Iterate through (cvFieldSplits) for iSplit = 1 : numel(cvFieldSplits)
% Access next-level within (cvFieldSplits), which will either be a % further sub-struct or else the final, desired field: outValue = outValue.(cvFieldSplits{iSplit}); end
% Handle failure catch exception … end
————————————–
Hope s/o finds this useful. Any comments appreciated,
댓글 수: 3
채택된 답변
추가 답변 (1개)
Paul Jordan
2018년 11월 14일
A.B.C.D = 50;
s = {'B','C','D'};
getfield(A,s{:})
ans =
50
댓글 수: 1
Cristian Constantinescu
2019년 2월 25일
편집: Cristian Constantinescu
2019년 2월 25일
This is such a concise and elegant solution to something I've been searching for a while.
Thank you!
참고 항목
카테고리
Help Center 및 File Exchange에서 Structures에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!