朱莉娅在矩阵中找到(行,列)而不是索引 [英] julia find in matrix with (row,col) instead of index
本文介绍了朱莉娅在矩阵中找到(行,列)而不是索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在 Julia 中,您可以通过以下方式找到矩阵中元素的坐标:
In Julia you can find the coordinates of elements in a matrix via:
julia> find( x -> x == 2, [ 1 2 3; 2 3 4; 1 0 2] )
3-element Array{Int64,1}:
2
4
9
这些值是正确的,但我更希望得到 (row,col) 元组.
These values are correct but I would prefer that I would get the (row,col) tuples instead.
(1,2)
(2,1)
(3,3)
在 Julia 中实现这一目标的最简单方法是什么?
What is the easiest way to achieve this in Julia?
推荐答案
我不相信有内置的方法可以做到这一点,但这里有一个函数可以做到这一点
I don't believe there is an inbuilt way to do it, but here is a function to do it
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
例如
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)
如果有大量的项目满足条件,那么分两次执行可能会更有效,但我对此表示怀疑.
If a large number of items satisfy the condition it might be more efficient to do it in two passes, but I doubt it.
对于较新版本的 Julia 替换
For newer versions of Julia replace
out = (Int,Int)[]
与
out = Tuple{Int, Int}[]
这篇关于朱莉娅在矩阵中找到(行,列)而不是索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文