## How to make dynamic variable names (A1, A2, ..., An) with "for" loop? Using "eval" "num2str"?

### Italo (view profile)

on 13 Nov 2013
Latest activity Commented on by Bruno Pop-Stefanov

### Bruno Pop-Stefanov (view profile)

on 22 Jan 2014

Hello community,

my knowledge of Matlab is limited, I admit it. So, I am sorry if I am going to make mistakes.

I have to create a series of variable using a "for" loop.

I make this:

--------------------------

```for i=1:3
```
```eval(['A' num2str(i) '= i'])
```
```end
--------------------------
```

and it works well, it makes 3 variables A1, A2, A3.

But I need to use this variables to make other variables B1, B2, B3 where Bi=Ai*i. So I should have B1=A1*1=1, B2=A2*2=2*2=4, B3=A3*3=3*3=9

I tried something like this:

----------------------------

```for i=1:3
```
```eval(['A' num2str(i) '= i'])
eval(['B' num2str(i) '= 'A' num2str(i) '*i])
```
```end
------------------------------
```

but it gives me error and it doesn't work. Of course I simplified things, the real code is a bt more complicated but I need to know the basics of how this could work.

Thank you

Muna

### Muna (view profile)

on 22 Jan 2014
```for i=1:3
genvarname('A',  num2str(i));
eval(['A' num2str(i) '= i'])
genvarname('B',  num2str(i));
eval(['B' num2str(i) '= A' num2str(i) '*i'])
end
```

## Products

No products are associated with this question.

on 22 Jan 2014
Edited by Amit

### Amit (view profile)

on 22 Jan 2014

Italo, I am glad you're trying out things on matlab.

Matlab is very good with matrixes. What you're doing in these can be done much easily. For example:

```A = 1:3;
B = A.*A; %
```

You can find many tutorials online on how to use MAtlab. For example: http://www.mathworks.com/academia/student_center/tutorials/launchpad.html

Amit

### Amit (view profile)

on 22 Jan 2014

In you code:

```for i=1:3
eval(['A' num2str(i) '= i'])
eval(['B' num2str(i) '= A' num2str(i) '*i']) % Issue was Here. Notice the positions of '
end
```
Bruno Pop-Stefanov

### Bruno Pop-Stefanov (view profile)

on 22 Jan 2014

I would like to add that eval is #1 in this list: Top 10 MATLAB code practices that make me cry