Assigning input string as variable name
52 次查看(过去 30 天)
显示 更早的评论
Hi everyone, I have a quick question. I would like to ask the user to input the name of a variable and then use that string as a new variable name. For example, say I have the value [0 1 2 3 4]. I want to ask the user to give the name he would like to that variable.
So, for example:
x = input('Enter the name of the new variable: ') Say the user enters: new_var
I want:
new_var = [0 1 2 3 4]
Can someone explain how to do this?
Thanks for the help
2 个评论
采纳的回答
Jan
2012-7-4
This method will be insecure: Imagine the users selects a name, which is already used in your program. Then there is no way to avoid a crash reliably.
Another problem will be evil users, who type:
"system('format C:); y"
Then eval will assign y after it has crashed your computer. I admit, this will not be the standard case. But there are a lot of possible problems, which are less brute.
2 个评论
Jan
2012-7-5
@David: Users will create typos, whenever it is possible.
When you will get problems with EVAL-approachs in the future, remember this thread and read the questions of hundrets of other forum users, who suffered from the disgraces of EVAL also. The user-controlled naming of variables is a bad programming practize.
更多回答(3 个)
Andrei Bobrov
2012-7-4
编辑:Andrei Bobrov
2012-7-4
x = input('Enter the name of the new variable: ','s');
eval([x,'=0:4;']);
2 个评论
Arash Roozitalab
2018-4-18
Hello. One might use
assignin('base',var_name, value)
to assign a
value
to a string
var_name = "given_name"
1 个评论
Stephen23
2018-4-18
编辑:Stephen23
2018-4-18
Note that assignin suffers from all of the same problems as eval does: slow, complex, obfuscated code, buggy, and hard to debug. This does not depend on which command is used, but these problems are caused by the act of magically assigning values to variable names dynamically. See:
Beginners wanting to learn how to write neat, efficient MATLAB code that is easy to debug should focus on keeping their data in as few arrays as possible, and use indexing to access it. As has already been discussed many times on this forum, they should avoid using eval, assignin, etc.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!