Using a string output to access a variable with the same name.
2 次查看(过去 30 天)
显示 更早的评论
Hello!
I'm new to MATLAB. Forgive me if this is trivial.
I have a 8x2 cell array called "*shipNames*" where column 1 is a list of numbers 1:8, and column 2 is the name of a series of variables (i.e. names of different ships).
I'm writing a code with user input, and the first thing I want the user to do is specify the ship whose data they are interested in.
load shipData;
shipNames
shipSelect=input('enther the corresponding number of the ship you wish to analyze');
currentShip=shipNames(shipSelect,2)
The return of currentShip is the name of the array containing data for that ship and this is a string. For example, if 'Titanic' the return of the above script, Titanic (a 10x3 array) is the variable that I want to analyze.
Here's where things get tricky (maybe)...
Instead of referring to Titanic as a variable, I'd rather write my code to look at currentShip. Essentially, I want to create a mask for Titanic called currentShip.
Hopefully this makes some sense! Thanks for your help!
0 个评论
回答(2 个)
Daniel Shub
2011-11-22
If you change your code slightly you can do this pretty cleanly.
data = load(shipData);
shipNames = data.shipNames;
...
currentShip = shipNames(shipSelect,2) % I don't think this does what you think it does.
currentShipName = currentShip;
currentShip = data.(currentShipName);
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!