create a number of variables in workspace and assign value to them using input command
Show older comments
i want to write a script that first gets the number of inputs(e.g:n=4) and then creates the respective variables(e.g:var1,var2,var3,var4) in workspace so that they can be assigned values(integer or matrix) by user using the 'input' command so that they can be used in my equations.i've tried something like this but it doesn't even produce variables in workspace:
1.n=input('number of inputs=');
2.for i=1:n
3.fprintf('var%d=',i)
4.eval(['var',num2str(i)])=input('')
5.end
notice that i can't use the following script:
1.for i=1:n
2.fprintf('var%d=',i)
3.var(i)=input('')
4.end
because in this script it creates only one variable in workspace; a matrix named var, and the values will be stored in its cells(therefor the inputs can't be matrices.) also i'm interested to know how exactly i should use the 'eval' command and when.thank you.
Answers (2)
Jan
on 20 Oct 2016
2 votes
Don't do this! Do not hide indices in the names of variables. Do not create variables dynamically.
3 Comments
hosein Javan
on 20 Oct 2016
Adam
on 20 Oct 2016
To use a cell array you need to use { }, not ( ). There are numerous links in the thread that Jan linked to that point to how to use cell arrays.
hosein Javan
on 20 Oct 2016
KSSV
on 20 Oct 2016
1 vote
It is not recommended to name the variables as you said. Refer the following link.
1 Comment
hosein Javan
on 20 Oct 2016
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!