Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Array of CartesianIndex to 2D-Matrix in Julia

Tags:

arrays

julia

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

like image 647
arash javanmard Avatar asked Dec 17 '22 19:12

arash javanmard


1 Answers

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.

like image 74
tholy Avatar answered Feb 12 '23 16:02

tholy