Converting Array of CartesianIndex to 2D-Matrix in Julia

匿名 (未验证) 提交于 2019-12-03 01:40:02

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!