julia在矩阵中找到(row,col)而不是index

can*_*his 5 matrix find julia

在Julia中,您可以通过以下方式找到矩阵中元素的坐标:

julia> find( x -> x == 2, [ 1 2 3; 2 3 4; 1 0 2] )
3-element Array{Int64,1}:
 2
 4
 9
Run Code Online (Sandbox Code Playgroud)

这些值是正确的但我宁愿我得到(row,col)元组.

(1,2)
(2,1)
(3,3) 
Run Code Online (Sandbox Code Playgroud)

在朱莉娅实现这一目标的最简单方法是什么?

Iai*_*ing 5

我不相信有一种内置的方法可以做到这一点,但这是一个功能

function findmat(f, A::AbstractMatrix)
  m,n = size(A)
  out = (Int,Int)[]
  for i in 1:m, j in 1:n
    f(A[i,j]) && push!(out,(i,j))
  end
  out
end
Run Code Online (Sandbox Code Playgroud)

例如

julia> findmat(x->x==2, [ 1 2 3; 2 3 4; 1 0 2] )
3-element Array{(Int64,Int64),1}:
 (1,2)
 (2,1)
 (3,3)
Run Code Online (Sandbox Code Playgroud)

如果大量的物品满足条件,那么两次通过可能会更有效率,但我对此表示怀疑.