问题描述
我有一个变量 a = 1
.我想生成一个形式的变量名:
I have a variable a = 1
. I want to generate a variable name of the form:
variableNumber
所以在这个例子中,我想要
So in this example, I would want
a1
a2
a3
作为变量.我该怎么做?
as variables. How can I do that?
推荐答案
试试genvarname
.
varname = genvarname(str)
是使用的基本语法.MATLAB 文档提供了将此函数与排除列表一起使用的详细示例(用于确保唯一的变量名称).您将不得不使用 eval
或其他函数(例如,前面的答案中提到的 assignin
)来使用此变量名.
is the basic syntax for use. MATLAB documentation has detailed examples of using this function with an exclusion list (for ensuring unique variable names). You will have to use eval
or another function (e.g. assignin
, mentioned in an earlier answer) to utilise this variable name.
要完整回答这个问题,
varnamelist = genvarname({'a','a','a','a','a'});
for l=1:length(varnamelist)
eval([varnamelist{l} '= l^2']);
end
当然,还有更有效的方法可以为 genvarname
组合一个输入列表,这留作练习 ;)
Of course, there are more efficient ways of putting together an input list for genvarname
, this is left as an exercise ;)
如果您关心性能,请注意 eval
可能会大大降低脚本/函数的速度;如果您需要动态变量命名,我个人建议使用 struct 或 cell 数据类型.
If you're concerned about performance, note that eval
may slow down the script/function greatly; personally I would recommend the use of struct or cell datatypes if you need dynamic variable naming.
这篇关于如何在 MATLAB 中将数字连接到变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!