How to concatenate a number to a variable name in MATLAB?

前端 未结 5 1779
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 07:17

I have a variable a = 1. I want to generate a variable name of the form:

variableNumber  

So in this example, I would want

5条回答
  •  鱼传尺愫
    2020-11-27 08:15

    Try genvarname.

    varname = genvarname(str)
    

    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.

    To answer the question completely,

    varnamelist = genvarname({'a','a','a','a','a'});
    for l=1:length(varnamelist)
      eval([varnamelist{l} '= l^2']);
    end
    

    Of course, there are more efficient ways of putting together an input list for genvarname, this is left as an exercise ;)

    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.

提交回复
热议问题