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,
采纳的回答
更多回答(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!