Have an error with dot, while searching value in struct

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

 Réponse acceptée

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 commentaires

Thank you!
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

Connectez-vous pour commenter.

Plus de réponses (2)

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
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})

Catégories

En savoir plus sur Characters and Strings dans Centre d'aide et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by