Interpolation of expression

Is there a more elegant way of interpolating x_i = i, without having to work with strings?

This is what I am using now:

for i = 1:3
    eval(Meta.parse("x$i = $i"))

I haven’t figured out metaprogramming yet :frowning:.

[:($(Symbol("x" * string(i))) = $(i)) for i in 1:3]

but, unless this is only for an MWE, you are probably much better off with another structure, eg a Vector, or a Dict.

Yes, that’s a MWE.

Wow, I thought that would be more succinct. I’d have to construct many Symbols that way, which would result in not very readable code.

Symbol("x", i) also works.

1 Like

When you run into problems like this, it is very likely that you are using a non-idiomatic solution, and may not even need metaprogramming, but it is hard to say more without some context.

1 Like

There are lots of useful macros in Base.Cartesian for this sort of thing:

julia> @macroexpand @nextract 3 x d->2d
    x_1 = 2
    x_2 = 4
    x_3 = 6