假设我们在 Julia 中有一组笛卡尔索引
julia> typeof(indx)
Array{CartesianIndex{2},1}
Run Code Online (Sandbox Code Playgroud)
现在我们想使用 PyPlot 将它们绘制为散点图。所以我们应该在转换INDX -阵列笛卡尔到一个二维矩阵,所以我们可以绘制它是这样的:
PyPlot.scatter(indx[:, 1], indx[:, 2])
Run Code Online (Sandbox Code Playgroud)
如何将Array{CartesianIndex{2},1}类型的Array转换为Array{Int,2}类型的 2D-Matrix
顺便说一下,这里是如何生成笛卡尔索引的虚拟数组的代码片段:
A = rand(1:10, 5, 5)
indx = findall(a -> a .> 5, A)
typeof(indx) # this is an Array{CartesianIndex{2},1}
Run Code Online (Sandbox Code Playgroud)
谢谢
一种可能的方法是hcat(getindex.(indx, 1), getindex.(indx,2))
julia> @btime hcat(getindex.($indx, 1), getindex.($indx,2))\n 167.372 ns (6 allocations: 656 bytes)\n10\xc3\x972 Array{Int64,2}:\n 4 1\n 3 2\n 4 2\n 1 3\n 4 3\n 5 3\n 2 4\n 5 4\n 1 5\n 4 5\n
Run Code Online (Sandbox Code Playgroud)\n\n但是,请注意,您不需要(因此可能不应该)将索引转换为二维矩阵形式。你可以简单地做
\n\nPyPlot.scatter(getindex.(indx, 1), getindex.(indx, 2))\n
Run Code Online (Sandbox Code Playgroud)\n
一个简单而通用的方法是
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
Run Code Online (Sandbox Code Playgroud)
这适用于任何维度,使第一个维度成为 CartesianIndex 的索引。