如何在MATLAB中将数字连接为变量名? [英] How to concatenate a number to a variable name in MATLAB?

查看:1176
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆