Create variables with names from strings
Asked Answered
H

6

17

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.

Handcart answered 19/4, 2013 at 7:24 Comment(1)
See MATLAB FAQ: How can I create variables A1, A2,...,A10 in a loop?Downwash
D
28

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
Decalescence answered 19/4, 2013 at 7:32 Comment(7)
Wow thanks, very simple. And yes, I will use cells but also this method you presented here ;)Handcart
I really discourage you from using eval to pop incremental variables in your workspace. If you want a name create a structure: s.(sprintf('x%d', i)) = i;Apennines
why is this not recommended?Cowled
@CharlieParker It makes your code hard to read (just compare my two solutions) and forces you to use eval again to iterate through your variables which is unnecessarily complicated. It makes your code very difficult to debug and adds in more room for error. Think about how you would find the largest x in the two solutions as an example of how complicated it's going to be if you use eval! Also it clutters your workspace with all those variables which you don't need. This is what arrays exist for! It is a sloppy, lazy way yo code that shows you didn't take the time to plan properly.Decalescence
@CharlieParker eval is also fairly slow because the optimizer can't know what it's going to do.Brownie
@patrickvacek that's a great point. Do you have a link to a test demonstrating this maybe?Decalescence
@Decalescence not readily available, but the idea is straight from the source: mathworks.com/help/matlab/matlab_prog/…Brownie
D
5

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

Disciplinarian answered 19/4, 2013 at 7:51 Comment(3)
Thanks. I will use arrays instead of cells. The example in my question was just very simple in order to have an easy question for the information I'm looking for. What I'm actually doing isn't as naive as my question :pHandcart
@bdecaf: btw genvarname is part of core MATLABDownwash
oh my bad. I could have sworn it was part of that toolbox.Disciplinarian
F
4
for k=1:10
   assignin('base', ['x' num2str(k)], k)
end
Flocky answered 17/1, 2014 at 14:18 Comment(1)
suggest changing 'base' to 'caller'. That way, AIUI, it ought to work anywhere where somebody is not paying specific attention to workspaces.Plaster
D
2

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

Dulin answered 26/2, 2014 at 10:15 Comment(0)
H
1

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.

Handcart answered 19/4, 2013 at 7:54 Comment(1)
In future, you can actually edit my answer if there are small mistakes like this. There is an edit link at the bottom. If you don't have enough reputation you can also just leave a comment and someone else will make the edit for you. I've fixed mine now ;)Decalescence
R
0

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);
Reld answered 17/12, 2013 at 9:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.