Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

julia find in matrix with (row,col) instead of index

Tags:

find

matrix

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

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?

like image 780
cantdutchthis Avatar asked Oct 04 '14 20:10

cantdutchthis


2 Answers

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}[]
like image 191
IainDunning Avatar answered Oct 29 '22 22:10

IainDunning


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

like image 22
Jake Rutterford Avatar answered Oct 29 '22 21:10

Jake Rutterford