create a new variable whos name is conditional

Hi. How can I creat a new variable whose name I dont know yet. A simple example is below. Thanks
>> [a,b,c]=xlsread('myfile.xlsx')
a =
[]
b =
'new_var'
c =
'new_var'
.... now I want to create a variable whose name is the same as the string taken from b . i.e I want to creat a variable with name new_var . and then give it a value ( new_var=10). How?

 採用された回答

Mischa Kim
Mischa Kim 2014 年 2 月 9 日
編集済み: Mischa Kim 2014 年 2 月 9 日

0 投票

Use the genvarname command.
mv = genvarname('my_varname');
eval([mv '= 123;']);
my_varname

3 件のコメント

Milad
Milad 2014 年 2 月 9 日
I dont know the name of the variable. The name is imported from excel. (You named it my_varname).
what is the code for generating the name and giving a value of 10 to it?
Mischa Kim
Mischa Kim 2014 年 2 月 9 日
編集済み: Mischa Kim 2014 年 2 月 9 日
Milad, it is pretty much the same. From your code, b is a string, just like
b = 'new_var'
mv = genvarname(b);
eval([mv '= 10;']);
new_var
In other words, you create (generate) a variable name with the string contained in b, then evaluate the command sequence [mv '= 10;'] which puts the newly generated variable with its content in the workspace.
Milad
Milad 2014 年 2 月 9 日
編集済み: Milad 2014 年 2 月 9 日
Thanks Mischa. I just understood what you was saying. you were right. The point was that when I read from excel, I should use genvarname like this :
mv=genvarname(b{1})
Thanks for introducing this command and for ur patience.

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

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 2 月 9 日
編集済み: Azzi Abdelmalek 2014 年 2 月 9 日

0 投票

You can do it like:
varname='new_var'
assignin('base',varname,[1 2 3])
new_var
But this is not a good idea like you can read it in the link

2 件のコメント

Milad
Milad 2014 年 2 月 9 日
In your code you already know the name of variable. suppose that you dont know what is written in excel file!
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 2 月 9 日
I don't know the name of the variable
[a,b,c]=xlsread('myfile.xlsx')
assignin('base',b,[1 2 3])

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

カテゴリ

ヘルプ センター および File ExchangeMATLAB についてさらに検索

製品

質問済み:

2014 年 2 月 9 日

編集済み:

2014 年 2 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by