Access to a structure value with the field path in a String form
32 views (last 30 days)
Show older comments
Hi,
I don't know how to access to a specific array stored in a structure by using the field path stored in a String form. The following code shows my issue:
clear all;
clc;
Struct.a.b.c.d = [1 2 3; 4 5 6]; % Structure containing the Matrix
structString = 'a.b.c.d(:,1)'; % String with the desired path
Ideally, I would like to access to the matrix with something like:
value = Struct.(structString)
But it doesn't work...
Thanks in advance for your help!
0 Comments
Accepted Answer
Walter Roberson
on 10 Aug 2015
The function below only handles plain fields, no indexing. There could be some justification for extending it to handle indexing of the final element, but indexing anywhere else gets problematic, requiring more advanced checking
Sample:
Struct.a.b.c.d = [1 2 3; 4 5 6]; % Structure containing the Matrix
structString = 'a.b.c.d'
t = struct_stridx(Struct, structString);
t = t(:,1);
function v = struct_stridx(S, fieldlist)
fn = regexp(fieldlist, '\.', 'split');
bad_fields = fn(cellfun(@isempty,regexp(fn, '^[A-Za-z][A-Za-z0-9_]*$')));
if ~isempty(bad_fields)
error('Only plain fieldnames are allowed. First invalid one is "%s"', bad_fields{1});
end
v = S;
for K = 1 : length(fn)
thisfn = fn{K};
if isfield(v, thisfn)
if length(v) == 1
v = v.(thisfn);
else
error('MATLAB:dotRefOnNonScalar', 'Dot name reference on non-scalar structure. Field "%s"', strjoin(fn(1:K), '.'));
end
else
error('Field "%s" does not exist in structure', strjoin(fn(1:K), '.'));
end
end
end
More Answers (1)
Image Analyst
on 9 Aug 2015
Why are you trying to get a string involved in this at all? Why not just get the values directly from the structure:
value = Struct.a.b.c.d(:,1)
I just don't see any need to involve a string at all.
See Also
Categories
Find more on Data Type Conversion in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!