unexpected behaviour inside for loop
I am trying to use @tullio inside a loop to construct an array part by part:
julia> x = zeros(2,2,3)
julia> for k in 1:3
z = reshape(range((k-1)*4+1, stop=k*4), 2,2)
@tullio x[i,j,k] = z[i,j]
end
The result is kind of surprising:
julia> x
2×2×3 Array{Float64, 3}:
[:, :, 1] =
9.0 11.0
10.0 12.0
[:, :, 2] =
9.0 11.0
10.0 12.0
[:, :, 3] =
9.0 11.0
10.0 12.0
This means in @tullio x[i,j,k] = z[i,j], k is taken as a new variable ranging from 1 to 3 rather than the predefined k. And I should use view to get what I want:
julia> for k in 1:3
z = reshape(range((k-1)*4+1, stop=k*4), 2,2)
x_catch = view(x, :,:,k)
@tullio x_catch[i,j] = z[i,j]
end
julia> x
2×2×3 Array{Float64, 3}:
[:, :, 1] =
1.0 3.0
2.0 4.0
[:, :, 2] =
5.0 7.0
6.0 8.0
[:, :, 3] =
9.0 11.0
10.0 12.0
Is it designed like this? Or maybe you should give some warning as in Einsum.jl?
Yes this is intentional. Every index is a new local variable, and is unaffected by whether one of the same name exists outside -- as it would be if you wrote for i in 1:2, k in 1:3 by hand.
But there is syntax for treating a particular index as a constant instead, using a dollar sign. So I think @tullio x[i,j,$k] = z[i,j] does what you want here, and introduces loops over only i and j.