Using subscript to index an array

Is there any macro or functionality that would allow me to index the elements of an array by subscript?

For eg if I had an array:
A = [1, 2, 3]
I would like to have code such as:

for i=1:length(A)
    A\_i = A\_i * 3
end

that would, in this example, multiply each element of A by 3.

My goals are for purely aesthetic/readability reasons. I think such a macro, if it exists, would be especially nice to index tensors or matrices. Thank you!

You could certainly write a macro that transforms variable names like Aᵢ or A_i (but not A\_i, which won’t parse as a variable name) into expressions A[i]. I don’t know of any existing code for this, off the top of my head.

I would tend to discourage you from doing this, however, except perhaps as a learning exercise — the resulting code will not be very readable to anyone else. It is generally better to write idiomatic Julia code.

6 Likes

For a while TensorCast.jl had a variant macro which understood A_i instead of A[i], although not Aᵢ. But I removed it in the name of simplicity. Right now:

julia> using TensorCast

julia> @cast A[i] = A[i] * 3  # equivalent to the loop above
3-element Vector{Int64}:
 3
 6
 9

julia> cast"A_i = A_i * 3"  # no longer exists
ERROR: LoadError: UndefVarError: `@cast_str` not defined
1 Like

I’ll sometimes write code like:

for (i, Aᵢ) in enumerate(A)
    A[i] = Aᵢ * 3
end

Of course, re-assigning Aᵢ doesn’t affect A itself so you still need to use indexed assignment there, but in some situations it can result in nicely-readable for loops.

4 Likes

Note that for (i, Aᵢ) in pairs(A) is slightly more general, here, since pairs doesn’t assume 1-based indexing.

6 Likes