如何在MATLAB中将数字连接为变量名? [英] How to concatenate a number to a variable name in MATLAB?
问题描述
我有一个变量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中将数字连接为变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!