PDA

View Full Version : How to set a variable name by user input in MATLAB


Weroc
May3-10, 07:34 PM
Think there is a simple solution to this but couldn't find any... Well as the title describes, i am wrote a program that generates, sorts, does some calculations and assings all results to a variable which is set before. Can i get the user assign the variable name which results will be assigned? I've been searching for more than 3 hours now but couldn't find any solution including MATLAB help, Doc files, Forums... I know it's not critically needed and program runs without problem ATM but let's say i like to spice things up :)

For further explanations,

Lets say my results are in x=1 2 3 ..... n
I want the user to assign the name which results will be in... like userinput=1 2 3 ..... n

Thanks for any help..

D H
May3-10, 07:42 PM
Have you looked at the eval() function?

Weroc
May4-10, 12:40 AM
Yes i did, but i am a starter and couldn't find the usage of eval or evalin for this situation the samples i saw in the doc and forums were a bit too complex for me to understand... I would really appriciate a decent usage pattern of eval or the exact code i need to make that happen :) either would be great.

Weroc
May5-10, 05:55 AM
Ok, i am trying to use eval for this thing but get an error message,

i just typed

s=input('test','s')
eval(s)

but matlab tells me that the values i enter for input are not defined before but, how can i define some variable before it's been created as i don't know which variable user will pick?

??? Error using ==> eval
Undefined function or variable 'k'.

Error in ==> Srala at 5
eval(s);

the part i am having problem is like below..

disp('NOT: Bu program rastgele belirlenen "n" kadar sayıyı sıralar ve bu değerlerli "s" değişkenine vektor olarak atar.')
n=input('Kaç adet veri sıralanacağını yazın = ');
s=input('test','s');
eval(s);
t=rand(1,n);
for x=1:n;
s(x)=min(t);
ind=find(t==min(t));
t(ind)=[];
end
disp ([num2str(n), ' Adet rastgele sayının sıralı hali: ', num2str(s)])

Also, i know there is a "Sort" command that does the same thing... but this part is used to program the sort function manually... It's like a challenge term :)

matonski
May5-10, 10:49 AM
This asks the user for the name of the variable and sets its value to 10:

value = 10;
variableName = input('Enter variable name: ', 's');
eval([variableName '=' num2str(value)])

It would be wise to check variableName first with isvarname to make sure it's a valid variable name.

Weroc
May5-10, 11:49 AM
thanks a lot for your answer, i can use the code you write to create a varname and assign values to it but the varname i want to let user set is seen as s(x) in the program... can i write some syntax to keep that place for the user assinged varname?