How can i create a variable in matlab that name stores in char variable?
3 views (last 30 days)
Show older comments
The problem is I have a structure with various field names and I can get them as symbolic variables. I need to create a variable that name is the same as name of one field name of the structure. How can I do that?
Accepted Answer
Walter Roberson
on 26 Jan 2011
Chances are that you do not need that and are advised not to do it. Please review the FAQ on this topic.
0 Comments
More Answers (2)
Jan
on 26 Jan 2011
Please consider Walter's suggestion. You can find a pile of questions concerning problems caused by this "poofing" methods. Creating variables dynamically is dangerous, confusing, hard to debug and slows down Matlab noticably. The wanted easier solution is to store the variables directly in a struct and avoid the conversion to and from single variables. Notice that "a(1)" can be a variable in one function and a private subfunction call in another function. In opposite to that "S.a(1)" accesses the variable stored in the field ever.
There is no "more simple" way to solve your problem. If you have to use EVAL, your approach includes a high complexity already. Therefore the best solution is to reduce the complexity of the data representation by packing the variables in a struct, array or cell array. Let me compare it with the question about a "simple" method to access variables, whose names are written with light yellow on white paper. Of course, ImageAnalyst can solve this, but it is a much better idea to simply choose a more computer friendly data storage model!
If you'd be grateful for a valuable advice, follow Waltern's suggestion and take into account that this topic was included in the FAQ, because hundrets and thousands of others have struggeled with the same problem also. The FAQ was written for you.
Kind regards, Jan
0 Comments
Alexis
on 26 Jan 2011
1 Comment
Walter Roberson
on 26 Jan 2011
See for example Matt Fig's contribution,
http://www.mathworks.com/matlabcentral/fileexchange/26216-structure-fields-to-variables
Or see this contribution from Hoi Wong: http://www.mathworks.com/matlabcentral/fileexchange/23254-map-fields-of-a-structure-to-output-variables
See Also
Categories
Find more on Function Creation in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!