Find Structure Field using a string and modify content of data under this field
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Joel Affolter
el 3 de Oct. de 2019
Comentada: Joel Affolter
el 3 de Oct. de 2019
I am currently designing an app, where I want to modify the data of a 1 x 1 structure with 162 fields. The string of the fieldname can be chosen from a dropdown menu and the desired value of said field can be selected via an EditField.
So if, for example I want to change the value of the field "X" to the value "XValue"
app.ValueDropDown.Value = "X"
structure.X = Xvalue
However I want the App to change the value of roughly 50 fields, depending on what the user desires and I currently see no other way than to do that using 50 if functions.
FieldNameVariable = app.ValueDropDown.Value %The FieldNameVariable now is of type "Char"
FieldNameVariable = convertCharsToStrings(FieldNameVariable) %The FieldNameVariable now is of type "String"
if FieldNameVariable = "X"
structure.X = XValue
else FileNameVariable = "X2"
structure.x2= XValue
else FileNameVariable = "X3"
structure.x3= XValue
...
else FileNameVariable = "X50"
structure.x50= XValue
end
Not only is this quite tedious to program, by programming it this way, one does need to change the app code if a new field wants to be made avaible for change.
Does anyone know a way to select and change the values of a certain Field using a string identical to the Field-Name?
Thanks in advance
0 comentarios
Respuesta aceptada
Stephen23
el 3 de Oct. de 2019
Editada: Stephen23
el 3 de Oct. de 2019
You can use dynamic fieldnames:
fld = 'X';
S.(fld) = XValue;
ADDENDUM: Given that your example fields are numbered it is quite possible that you would be much better off using a non-scalar structure with indexing:
S(k).Xvalue = XValue;
Using a non-scalar structure with indexing would allow you to set/get the values of multple structure elements at once, and take advantage of other convenient syntaxes:
Más respuestas (0)
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!