Using a string output to access a variable with the same name.

3 次查看(过去 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!

回答(2 个)

Walter Roberson
Walter Roberson 2011-11-22

Daniel Shub
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);

类别

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