Question: searching a value in a multi-dimensional list, array or matrix


I couldn't find a command or tool for searching a value in a multi-dimensional list/array/matrix. Does it exist?. 

I wrote this:


multidimSearch := proc (pSearch, A, nStart := 1, nEnd := nops(A))

  local n_, pos_: 

  pos_ := 0:

  for n_ from max(nStart, 1) to min(nEnd, ops(A)) do

     if pSearch(A[n_]) then

       pos_ := n_:


     end if:

  end do:

  return pos_:

end proc:



pSearch: proc for searching

A: list, array, vector or matrix

nStart: 1st index to search in

nEnd: Last index to search in

Procedure returns the first index found or 0 if not.

Examples with a list:

> ss := [[1, 2, 3], [2, 3, 5], [2, 4, 5]]
> j:=1:
># search first index i such that ss[i, j]=2

> nPos := multidimSearch(u->(u[1]=2),A)

> nPos := 2 


># search next index i such that ss[i, j]=2

> nPos := multidimSearch(u->(u[1]=2),A,nPos+1)

> nPos := 2 


But I am not sure if this procedure is efficient for large lists or arrays and I would suggest (if this tool does not exist yet) a more efficient one.

César Lozada




Please Wait...