Create variables with names from strings

2019-01-01 13:32发布

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.

6条回答
浮光初槿花落
2楼-- · 2019-01-01 14:01

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.

查看更多
其实,你不懂
3楼-- · 2019-01-01 14:01

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);
查看更多
荒废的爱情
4楼-- · 2019-01-01 14:12

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
查看更多
梦醉为红颜
5楼-- · 2019-01-01 14:12

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

查看更多
与风俱净
6楼-- · 2019-01-01 14:14
for k=1:10
   assignin('base', ['x' num2str(k)], k)
end
查看更多
倾城一夜雪
7楼-- · 2019-01-01 14:15

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

查看更多
登录 后发表回答