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

12 Ansichten (letzte 30 Tage)
John F
John F am 22 Nov. 2011
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;
shipSelect=input('enther the corresponding number of the ship you wish to analyze');
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!

Antworten (2)

Walter Roberson
Walter Roberson am 22 Nov. 2011

Daniel Shub
Daniel Shub am 22 Nov. 2011
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);


Community Treasure Hunt

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

Start Hunting!

Translated by