在 Julia 中将 CartesianIndex 数组转换为二维矩阵 [英] Converting Array of CartesianIndex to 2D-Matrix in Julia

查看:18
本文介绍了在 Julia 中将 CartesianIndex 数组转换为二维矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们在 Julia 中有一个笛卡尔索引数组

let's say we have an array of cartesian indices in Julia

julia> typeof(indx)
Array{CartesianIndex{2},1}

现在我们想使用 PyPlot 将它们绘制为散点图.所以我们应该将笛卡尔 indx-Array 转换为 2D-Matrix 以便我们可以像这样绘制它:

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])

如何将 Array{CartesianIndex{2},1} 类型的数组转换为 Array{Int,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}

谢谢

推荐答案

一种可能的方法是 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

但是,请注意,您不需要(因此可能也不应该)将索引转换为 2D 矩阵形式.你可以简单地做

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))

这篇关于在 Julia 中将 CartesianIndex 数组转换为二维矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆