Create variables with names from strings

核能气质少年 提交于 2019-11-26 05:48:07

问题


Let\'s assume that I want to create 10 variables which would look like this:

x1 = 1;
x2 = 2;
x3 = 3;
x4 = 4;
.
.
xi = i;

This is a simplified version of what I\'m intending to do. Basically I just want so save code lines by creating these variables in an automated way. Is there the possibility to construct a variable name in Matlab? The pattern in my example would be [\"x\", num2str(i)]. But I cant find a way to create a variable with that name.


回答1:


You can do it with eval but you really should not

eval(['x', num2str(i), ' = ', num2str(i)]); %//Not recommended

Rather use a cell array:

x{i} = i



回答2:


I also strongly advise using a cell array or a struct for such cases. I think it will even give you some performance boost.

If you really need to do so Dan told how to. But I would also like to point to the genvarname function. It will make sure your string is a valid variable name.

EDIT: genvarname is part of core matlab and not of the statistics toolbox




回答3:


for k=1:10
   assignin('base', ['x' num2str(k)], k)
end



回答4:


Although it is long overdue, i justed wanted to add another answer.

the function genvarname is exactly for these cases

and if you use it with a tmp structure array you do not need the eval cmd

the example 4 from this link is how to do it http://www.mathworks.co.uk/help/matlab/ref/genvarname.html

 for k = 1:5
   t = clock;
   pause(uint8(rand * 10));
   v = genvarname('time_elapsed', who);
   eval([v ' = etime(clock,t)'])
   end

all the best

eyal




回答5:


If anyone else is interested, the correct syntax from Dan's answer would be:

eval(['x', num2str(i), ' = ', num2str(i)]);

My question already contained the wrong syntax, so it's my fault.




回答6:


I needed something like this since you cannot reference structs (or cell arrays I presume) from workspace in Simulink blocks if you want to be able to change them during the simulation.

Anyway, for me this worked best

assignin('base',['string' 'parts'],values);


来源:https://stackoverflow.com/questions/16099398/create-variables-with-names-from-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!