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.

回答 (1 件)

Stephen23
Stephen23 2017 年 3 月 14 日
編集済み: Stephen23 2017 年 3 月 14 日

1 投票

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.

カテゴリ

質問済み:

2017 年 3 月 14 日

編集済み:

2017 年 3 月 14 日

Community Treasure Hunt

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

Start Hunting!

Translated by