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
0 个评论
采纳的回答
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:
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Structures 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!