Edit: Ah, sorry, didn’t see you had discovered that already. You need to convert the cartesian indices to a tuple before indexing first, like the error suggests. Maybe
julia> for i in 1:2, j in 1:3
xx[i, j] = CartesianIndices((2, 2))[location[i, j]][1]
end
julia> for i in 1:2, j in 1:3
yy[i, j] = CartesianIndices((2, 2))[location[i, j]][2]
end
julia> xx
2×3 Matrix{Float64}:
1.0 2.0 1.0
2.0 1.0 2.0
julia> yy
2×3 Matrix{Float64}:
1.0 1.0 2.0
1.0 2.0 2.0
This is the result what I need. But I don’t think loop is the best way.
Matlab to Julia requires significant unlearning of bad habits. Another one for free: whenever you type rand(1) or rand(n,1), you almost certainly want rand() or rand(n).
@ murphyk I try to use function sub2indv which @ murphyk wrote.
function subv2ind(shape, cindices)
"""Return linear indices given vector of cartesian indices.
shape: d-tuple of dimensions.
cindices: n-iterable of d-tuples, each containing cartesian indices.
Returns: n-vector of linear indices.
Based on:
https://discourse.julialang.org/t/psa-replacement-of-ind2sub-sub2ind-in-julia-0-7/14666/8
Similar to this matlab function:
https://github.com/tminka/lightspeed/blob/master/subv2ind.m
"""
lndx = LinearIndices(Dims(shape))
n = length(cindices)
out = Array{Int}(undef, n)
for i = 1:n
out[i] = lndx[cindices[i]...]
end
return out
end
julia> A = [1 2 1; 2 2 1]
2×3 Matrix{Int64}:
1 2 1
2 2 1
julia> subv2ind((2, 2), Tuple.(zip(A[1, :], A[2, :])))
3-element Vector{Int64}:
3
4
1