Reputation: 1
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]
for i = 1:3
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]
for i = 1:3
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. Maybe I don't even need to write a loop to do this--I'm open to completely different methods of accomplishing this as well.
Upvotes: 0
Views: 1659
Reputation: 33249
As others have said, it's a bit questionable whether one should do this, but if this is really what you want to do, here's how you can do it:
A = [1, 2, 3]
for i = 1:3
@eval $(Symbol("x$i")) = $(A[i])
end
after which these global variables are assigned:
julia> x1, x2, x3
(1, 2, 3)
The inner expression is equivalent to writing this:
eval(:($(Symbol("x$i")) = $(A[i])))
In other words, you construct and then eval an assignment expression where the left hand side is the symbol x$i
and the right hand side is the value of A[i]
.
Note that you can only define global variables like this, not local ones because eval
always operates in global scope. Other languages have "local eval", Julia does not because the very possibility of local eval in a language makes optimization much harder.
Upvotes: 3
Reputation: 42194
The short answer is that if you do not know how to do it, than it surely means that you do not need it. And like pointed by DNF for all normal language use cases it is definitely not a good practice.
The functionality that you are looking for can be accomplished by meta-programming. Here is a simple example code (again do not use it unless you already have great experience with the language and now wanting to learn meta-programming, eg. because you want to construct your own DSL on top of Julia):
macro definevars(name::String, a::Symbol, len::Int)
res = :(;)
for i in 1:len
varname = Symbol(string(name,i))
push!(res.args, esc(:($varname = $a[$i])))
end
res
end
Now let us test it:
julia> B = [5,6,7];
julia> @definevars "b" B 3;
julia> b1, b2, b3
(5, 6, 7)
There are many performance issues here. You might want to use StaticArrays
combined with @generated
functions.
Upvotes: 1