可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
let's say we have an array of cartesian indices in Julia
julia> typeof(indx) Array{CartesianIndex{2},1}
Now we want to plot them as a scatter-plot using PyPlot. so we should convert the indx-Array of Cartesian to a 2D-Matrix so we can plot it like this:
PyPlot.scatter(indx[:, 1], indx[:, 2])
How can i convert an Array of type Array{CartesianIndex{2},1} to a 2D-Matrix of type Array{Int,2}
By the way here is a code snippet how to produce a dummy Array of cartesianindex:
A = rand(1:10, 5, 5) indx = findall(a -> a .> 5, A) typeof(indx) # this is an Array{CartesianIndex{2},1}
Thanks
回答1:
One possible way is hcat(getindex.(indx, 1), getindex.(indx,2))
julia> @btime hcat(getindex.($indx, 1), getindex.($indx,2)) 167.372 ns (6 allocations: 656 bytes) 10×2 Array{Int64,2}: 4 1 3 2 4 2 1 3 4 3 5 3 2 4 5 4 1 5 4 5
However, note that you don't need to - and therefore probably shouldn't - bring your indices to 2D-Matrix form. You could simply do
PyPlot.scatter(getindex.(indx, 1), getindex.(indx, 2))
回答2:
An easy and generic way is
julia> as_ints(a::AbstractArray{CartesianIndex{L}}) where L = reshape(reinterpret(Int, a), (L, size(a)...)) as_ints (generic function with 1 method) julia> as_ints(indx) 2×9 reshape(reinterpret(Int64, ::Array{CartesianIndex{2},1}), 2, 9) with eltype Int64: 1 3 4 1 2 4 1 1 4 2 2 2 3 3 3 4 5 5
This works for any dimensionality, making the first dimension the index into the CartesianIndex.