Help about 'calling a variable from workspace by using input command'

Hi, here is my question; I have some values in workspace which ones names are VarName1, VarName2... And I want to call them by using a input command.
For example
a = 'Enter the number of VarName';
number = input(a);
Then if I enter 18 as number input, it must call VarName18 from workspace. Please help me, thank you.

Antworten (1)

Stephen23
Stephen23 am 14 Mär. 2017
Bearbeitet: Stephen23 am 14 Mär. 2017
Do not access lots of variable names like that. It will make your code slow, complicated, and buggy:
Just keep all of your data in one variable, and use indexing. Then your task it trivially easy:
>> C{1} = 0:3;
>> C{2} = 4:6;
>> C{3} = 7:9;
>> idx = str2double(input('enter variable #: ','s'));
enter variable #: 2
>> C{idx}
ans =
4 5 6
Look at that: good program design using indexing made my code simple, efficient, and easy to understand. Any code that you write that accesses variable names will be slower, buggier, and more obfuscated.

Gefragt:

am 14 Mär. 2017

Bearbeitet:

am 14 Mär. 2017

Community Treasure Hunt

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

Start Hunting!

Translated by