3

So let's say I have a numpy array like this:

import numpy as np
mat = np.array([[4, 8, 1], [5, 10, 6]])

print(np.argmax(mat)) # prints 4
print(np.argmax(mat, axis=1)) # prints [1 1], index of maximum values along the rows

Does Kotlin have a similar (built in) function? I found a Kotlin bindings for NumPy, but I didn't find the function implemented.

Thanks in advance!

dzsezusz
  • 106
  • 9
  • [This question](https://stackoverflow.com/q/20762219/6629569) might be of use to you. – Abby Mar 10 '20 at 09:05

2 Answers2

4

Use withIndex() and maxByOrNull():

fun <T : Comparable<T>> Iterable<T>.argmax(): Int? {
    return withIndex().maxByOrNull { it.value }?.index
}
Marcin Mrugas
  • 973
  • 8
  • 17
  • This works for 1-dimensional arrays but not 2-dimensional ones. The numpy function for argmax takes an array and optionally an axis. Without an axis, the result is an integer as if you concatenated the arrays and returned the index of the max element. With an axis, it returns an array holding the indexes of the max values in each column (for axis 0) or row (for axis 1). https://numpy.org/doc/stable/reference/generated/numpy.argmax.html – mithunc Jul 22 '22 at 00:17
0

kotlin-numpy has been deprecated, but you can use the Multik library. It has an argmax function: https://kotlin.github.io/multik/multik-core/org.jetbrains.kotlinx.multik.api.math/-math/arg-max.htm

mithunc
  • 124
  • 2
  • 8