How can i generate a variable from the strings that i took from a csv file by xlsread function?

2 views (last 30 days)
I am using xlsread function as
[NUM,TXT,RAW]=xlsread('abc.xls');
I have a string in TXT output as, TXT(1,1)='time'
I want to generate a variable as the same value as TXT(1,1), in other words the name of the new variable must be "time".
I tried assignin and eval functions but was not succesful.

Answers (1)

Guillaume
Guillaume on 12 Jan 2015
First, don't do this. dynamic variable names are not a good idea. You loose any chance of the jit compiler making any optimisation to your code, debugging becomes more complex, and the code more obscure.
If you explain why you want to do it, we can give you some other options that will probably work better.
If you still insist on doing it, read on, but here be dragons:
You can either use assignin or eval. If you use assignin and you want the new variable to be local, you have to use assignin in a subfunction:
function createvariable(varname, value)
assignin('caller', varname, value); %varname is local to the calling function
end
If you use eval, the tricky bit is the conversion of the new value to string as there's no universal format.
varname = 'time'
eval(sprintf('%s = %d', varname, 12345)); %for integer
eval(sprintf('%s = %f', varname, 12.345); %for double. May loose some precision
%... even more complicated with complex data types unless you hardcode the value in the string.
Referring to the variable from now on, is exclusively with eval:
x = eval(varname) + 10;
As you can see, it's a mess.

Tags

Products

Community Treasure Hunt

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

Start Hunting!