Creating multiple inputs depending on conditions

Is there a way to create multiple inputs depending on initial condition? To be clear, for an example I want to create n inputs depending of numeric value of symbol n.
n=input('Input n');
and I enter 5 and I want to create 5 inputs automatically in real time, outputs should look like this:
a1=input('Input1')
a2=input('Input2')
a3=input('Input3')
a4=input('Input4')
a5=input('Input5')
Is that possible? Is there any way to create it?

1 件のコメント

Stephen23
Stephen23 2017 年 4 月 14 日
編集済み: Stephen23 2017 年 4 月 14 日
There are ways, but only if you want to write slow, buggy, obfuscated code with major security risks. The MATLAB documenatation specifically advises to avoid doing this. Every expert on this forum will tell you not to do this. No matter that beginners think that creating or accessing dynamic variable names is a great idea and will solve all of their problems, it won't. It just causes more problems.
Use indexing. Indexing is fast, efficient, simple to write, simple to debug, simple to read, simple to understand,... and is the best way to solve your task. Like this:
C = cell(1,5)
for k = 1:numel(C)
C{k} = input('blah','s');
end
See how easy that was? And it is fast, efficient, and so simple, that anyone can understand it.
Read this to know why dynamic variables names is a bad way to write code:

サインインしてコメントする。

 採用された回答

James Tursa
James Tursa 2017 年 4 月 14 日
編集済み: James Tursa 2017 年 4 月 14 日

1 投票

Yes, there is a way, but it is a bad idea to do so. Dynamically naming variables with trailing numbers like that makes it very difficult to use them downstream in a generic way. You would be better off using a cell array or the like. E.g.,
for k=1:n
a{k} = input(['Input' num2str(k)])
end
Now you can use natural indexing with a{k} downstream in your code instead of hard coding a1, a2, etc or resorting to eval( ). Or if the inputs are scalars simply ask the user to enter an n-element vector, and then you can use a(k) downstream in your code.

1 件のコメント

Tihomir Jevtic
Tihomir Jevtic 2017 年 4 月 14 日
Thank You very much! I needed this to dynamically generate inputs for initial conditions for solving differential equation with dsolve. Number of generated inputs (to enter initial condition expressions) is in relation with the order of differential equation. On the end I've modified a{k} = input(['Input' num2str(k)], 's'), to input it as a string. Thank You again.

サインインしてコメントする。

その他の回答 (1 件)

dpb
dpb 2017 年 4 月 14 日

1 投票

Of course, but I strongly recommend against building the N variables A1...AN. Ask the user for an array A instead with N elements.

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by