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
These values are correct but I would prefer that I would get the (row,col) tuples instead.
(1,2)
(2,1)
(3,3)
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
e.g.
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.
Edit:
For newer versions of Julia replace
out = (Int,Int)[]
with
out = Tuple{Int, Int}[]
In case anyone else finds this you can now use:
ind2sub(a, index)
It returns a tuple of subscripts into array a
corresponding to the linear index index
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With