indexlst(l,v)
func
©(l,v) return list of k|l[k]=v
©3nov01/dburkett@infinet.com
local k,r,j
{}→r ©Initialize result list ...
1→j ©... and result list index
for k,1,dim(l) ©Loop to test each list element
if l[k]=v then ©If list element matches target ...
k→r[j] ©... save index in result list
j+1→j ©... and update result list index
endif
endfor
return r ©Return result list
Endfunc
Since more than one list element may match the target value, the matching indices are returned as a
list. For example, if the list mylist is {5,4,7,3,2,1,1}, then indexlst(mylist,5) returns {1}, and
indexlst(mylist,1) returns {6,7}.
indexlst() returns an empty list {} if the target element is not in the list. So, this function could also be
used to determine if a list includes a particular element, by testing the returned result for dim() = 0.
This function can find the indices of the minimum and maximum list values, with the built-in min() and
max() functions. To find the indices of the minimum list element, use
indexlst(mylist,min(mylist))
which, for the example above, returns {6,7}. To find the indices of the maximum list element, use
indexlst(mylist,max(mylist))
which returns {3}.
Finding the indices of a particular element in a matrix is only slightly more complicated, and we can use
indexlst() to do the work, by converting the matrix to a list with
mat▶list(). Since indexlst() returns a
list, we must then convert the list indices to the equivalent matrix indices. This function implements
these ideas.
indexmat(m,v)
Func
©(mat,v) return matrix of [k,l]|mat[k,l]=v
©calls util\indexlst()
©4nov01/dburkett@infinet.com
local r,n,j,i,s,c
mat▶list(m)→r ©Convert the matrix to a list
util\indexlst(r,v)→r ©Find list indices of v
if r={} then ©Return empty string if no matching indices
return ""
else ©Convert list indices to matrix indices
dim(r)→c ©... get number of matching indicex
coldim(m)→n ©... get number of matrix columns
newmat(c,2)→s ©... make result matrix
for i,1,c ©... loop to convert indices
intdiv(r[i]-1,n)+1→j ©... find row index
3 - 30