Borrar filtros
Borrar filtros

create a number of variables in workspace and assign value to them using input command

6 visualizaciones (últimos 30 días)
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.

Respuestas (2)

Jan
Jan el 20 de Oct. de 2016
Don't do this! Do not hide indices in the names of variables. Do not create variables dynamically.
  3 comentarios
Adam
Adam el 20 de Oct. de 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
hosein Javan el 20 de Oct. de 2016
thanks Adam. that was all i needed to know to know that you can put everything in a cell array even a matrix. so i recommend anyone who has got a problem like mine just substitute [] with {} and the code should be like:
1.for i=1:n
2.fprintf('var%d=',i)
3.var{i}=input('')
4.end

Iniciar sesión para comentar.


KSSV
KSSV el 20 de Oct. de 2016
  1 comentario
hosein Javan
hosein Javan el 20 de Oct. de 2016
yes i know. i assume you mean to use a vector instead for some hardware acceleration reason, (one variable in workspace and the values in its cells) but as i mentioned i can't use a vector, normally when the inputs are common integers you can put them inside it, but when it's for matrices, it's different. i think you mean i must put the input matrices in a vector's cells and create a multidimensional array, but i don't know how. allow me to clarify the question. here's the problem: the program should receive a number of vectors(like [10], [1 2 5] ,etc) with different dimensions and save them somewhere(in variable, vector, etc) for further calculations. but the number of inputs is determined by the user. here's what i've been trying:
n=input('how many systems?');
for i=1:n
fprintf('num%d=',i)
num(i)=input('')
fprintf('den%d=',i)
den(i)=input('')
end
when i enter n=2, num1=[1], den1=[1 2 5], i get the error:"In an assignment A(I) = B, the number of elements in B and I must be the same."

Iniciar sesión para comentar.

Community Treasure Hunt

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

Start Hunting!

Translated by