In J it is trivial to find the minimum element of an array:
<./ 5 6 4 9
4
But how to find the index of the minimum element using J?
(In case this is an XY problem, I should say that I want the index rather than the value so that I can look up the corresponding elements in other arrays.)
I think that I would use this
ind=: I. @: (= <./)
It starts with the <./
which returns your lowest value and it uses =
as the other half of a monadic hook. Monadic hooks take the y
argument and apply the rightmost verb to it and then the left verb uses that as its right argument with the original y
as its left argument. So, (= <./) 5 6 4 9
is the same as 5 6 4 9 = 4
and this returns 0 0 1 0
. From there it is simple to use the monadic I.
(indices) to return the index of the value 1
which is of course 2
.
This also will return multiple indices if there is more than one least value.
ind 5 6 4 9 4
2 4
If you only want the first or the last value you can use the simpler monadic hooks that incorporate i.
(index of) or i:
(index of last):
indfirst =: i. <./
indfirst 5 6 4 9 4
2
indlast =: i: <./
indlast 5 6 4 9 4
4