How to change the name of a variable in a for loop

I would like to change the name of a variable within a for loop, using the loop index in the name of the variable.

I’ve tried the following syntax:

A= [1,2,3]
nargs = length(A)
for i = 1:nargs
    global x{i}
    x{i}=A[i]
end

This isn’t the right syntax, and googling has not led me to the correct syntax.

I’ve also tried

A= [1,2,3]
nargs = length(A)
for i = 1:nargs
    global x$i
    x$i=A[i]
end

My hope is to create three variables, x1, x2, and x3 each containing the appropriate element of A. I will not know the size of A beforehand, which is why I thought to do it this way.

1 Like

This works:

for i = 1:nargs
    @eval $(Symbol(:x, i)) = A[$i]
end

But you will pretty much always be better off using a vector or tuple instead, so I really wouldn’t recommend using this in non-toy code. You also don’t need global here, since eval always works in global scope.

5 Likes

Thank you!