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

2 visualizaciones (últimos 30 días)
John F
John F el 22 de Nov. de 2011
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!

Respuestas (2)

Walter Roberson
Walter Roberson el 22 de Nov. de 2011

Daniel Shub
Daniel Shub el 22 de Nov. de 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);

Categorías

Más información sobre Structures en Help Center y File Exchange.

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by