Have an error with dot, while searching value in struct

9 views (last 30 days)
Hello guys.
Have a little problem with searching parameter value in structure.
If I do like this:
m = data.CH4.td_function_diapason_1.entropy
Everything is okay
m =
'-4.6413037599999996'
but if I do like this
parametr = ({'td_function_diapason_1.entropy'});
parametr{1}
m = data.CH4.(parametr{1})
I get an error
ans =
'td_function_diapason_1.entropy'
Reference to non-existent field 'td_function_diapason_1.entropy'.
Error in parsing (line 13)
m = data.CH4.(parametr{1})
What's the problem?
This code works if it doesn't include a dot in parametr
parametr = ({'molar_mass'});
parametr{1}
m = data.CH4.(parametr{1})
ans =
'molar_mass'
m =
'0.016042999999999998'
Thank you

Accepted Answer

Walter Roberson
Walter Roberson on 16 Dec 2021
Dynamic field names cannot have multiple field names. You can only dynamically create one field name at a time.
data.CH4.td_function_diapason_1.entropy = '-4.6413037599999996'
data = struct with fields:
CH4: [1×1 struct]
parametr = {'td_function_diapason_1' 'entropy'}
parametr = 1×2 cell array
{'td_function_diapason_1'} {'entropy'}
subsref(data.CH4, struct('type', '.', 'subs', parametr))
ans = '-4.6413037599999996'
  2 Comments
Ivan Ivan
Ivan Ivan on 17 Dec 2021
Did like this:
s = size(parametr,2); %number of parametr columns
if s == 2 % 2 columns
m = data.(components{i}).(parametr{1}).(parametr{2})
else
m = data.(components{i}).(parametr{1})
end

Sign in to comment.

More Answers (2)

Steven Lord
Steven Lord on 16 Dec 2021
Dynamic field names works if the entry inside the parentheses is a field name. "a.b" is not a field name, it represents multiple levels of indexing.
data.CH4.td_function_diapason_1.entropy = 42;
You could use multiple levels of dynamic field names:
q = data.CH4.('td_function_diapason_1').('entropy')
q = 42
or you could use getfield.
s = 'td_function_diapason_1.entropy';
fn = split(s, '.'); % fn is a cell array
q2 = getfield(data.CH4, fn{:}) % use a comma-separated list
q2 = 42

Voss
Voss on 16 Dec 2021
Dynamic field names do not support nested fields like that. But you can do it in two separate dynamic field name references:
parametr = {'td_function_diapason_1'};
parametr2 = {'entropy'};
m = data.CH4.(parametr{1}).(parametr2{1})

Categories

Find more on Structures 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!