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

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

问题描述

假设我们在Julia中有一系列笛卡尔索引

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

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

现在,我们想使用PyPlot将它们绘制为散点图.所以我们应该将笛卡尔的 indx 数组转换为2D矩阵,以便我们可以像这样绘制它:

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数组转换为2D矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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