Find Structure Field using a string and modify content of data under this field

1 次查看(过去 30 天)
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

采纳的回答

Stephen23
Stephen23 2019-10-3
编辑:Stephen23 2019-10-3
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:
  1 个评论
Joel Affolter
Joel Affolter 2019-10-3
Hey Stephen,
Thanks for the super fast response, I will give it a look!
My fields are not numbered. I just used this notation to get my idea/problem across

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Structures 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by