How to use strings to access a multi-level structure?
18 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Cheng-Yu Lin
el 23 de Dic. de 2021
Comentada: Stephen23
el 24 de Dic. de 2021
I have some strings look like "TestParameter.Measurement.OutputValue" and values corresponding to each string. I want to creat a structure with the strings and assign the values to the structure.
For example, if the input string is "TestParameter.Measurement.OutputValue" and the corresponding value is 3, I hope do the thing as follow through a function:
TestParameter = struct;
TestParameter.Measurement.OutputValue = 3;
Also, the level of the structure is not fixed. How can I do what I want?
Thank you!
0 comentarios
Respuesta aceptada
Walter Roberson
el 23 de Dic. de 2021
Use setfield https://www.mathworks.com/matlabcentral/answers/1612735-have-an-error-with-dot-while-searching-value-in-struct#answer_856880
Más respuestas (2)
Cris LaPierre
el 23 de Dic. de 2021
You can use strings to build a structure, but I don't believe you can add multiple levels at once, and I don't believe you can dynamically create the first level.
str = split("TestParameter.Measurement.OutputValue",".")
TestParameter.(str(2)).(str(3)) = 3
2 comentarios
Stephen23
el 24 de Dic. de 2021
"but I don't believe you can add multiple levels at once"
Actually this is quite easy... see my answer.
Stephen23
el 23 de Dic. de 2021
Editada: Stephen23
el 23 de Dic. de 2021
The variable name should not be dynamically accessed:
Arbitrarily nested fieldnames can be accessed at once using SETFIELD and GETFIELD, for example:
S = struct();
T = 'ignorethis.Measurement.OutputValue';
F = regexp(T,'[^.]+','match'); % or SPLIT()
S = setfield(S,F{2:end},3)
Checking:
S.Measurement.OutputValue
More robust code would not store those nested fieldnames as one string/charvector, but as separate fieldnames.
Ver también
Categorías
Más información sobre Structures en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!