j→s[i,1] ©... save row index
r[i]-n*(j-1)→s[i,2] ©... find and save column index
endfor
endif
return s ©Return matrix of indices
EndFunc
The function returns an empty string ("") if the target value is not found. The calling program or function
can test the result with getType() to determine if there are any matching indices.
If the matrix m is
−2 −28−7
−59−7 −5
−20−39
−80−59
then indexmat(m,-2) returns the result
11
12
31
indicating that the element -2 is at indices [1,1], [1,2] and [3,1]. In the index matrix returned by
indexmat(), the first column is the row indices of the original matrix, and the second column is the
column indices. You can use rowDim() on the result matrix to determine the number of matching
elements.
As with the list index function, we can use indexmat() to find the indices of the minimum and maximum
matrix elements, but we must first use
mat▶list() in the argument of min() and max(), because those
functions return a row vector of column extrema for matrix arguments. So, to find the indices of the
minimum elements of matrix m, we use
indexmat(m,min(mat▶list(m)))
which returns [4,1], since there is only one element which is the minimum value of -8.
To find the maximum element indices, use
indexmat(m,max(mat▶list(m)))
which returns
22
34
44
and these are the indices of the maximum element 9.
indexmat() works on matrices of any row and column dimensions, and always returns a 2-column
matrix. Note that you can use a single row-index value to extract the individual indices for the result
matrix. For the example above, if we want the second index from the result, we use
[[2,2][3,4][4,4]][2]
which returns [3,4].
3 - 31