Home > Mobile >  Kotlin 2D array calculate mean by column
Kotlin 2D array calculate mean by column

Time:11-23

I have a 2D array and I want to calculate the mean by column. For example:

[[1,2,3],[4,5,6]] -> [2.5,3.5,4.5]

In python, I will simple do this

np.mean(array, axis=1)

How could I do it in Kotlin?

CodePudding user response:

Kotlin does not have 2D arrays, so it does not support operations for 2D arrays. Assuming we have an array of arrays and we know the size of each row is e.g. 3, we can get averages using the following:

val arr = arrayOf(
    arrayOf(1, 2, 3),
    arrayOf(4, 5, 6),
)

val result = (0 until 3).map { col ->
    arr.map { it[col] }.average()
}

println(result) // [2.5, 3.5, 4.5]

If you often perform such operations then you can look at Multik which is a multi-dimensional array implementation for Kotlin.

CodePudding user response:

Simply get the first array from each array in the 2D array, since the 2D array is essencially an array of arrays

var median = 0
for(k in array.indices) {
    median  = array[k][1]
}
median /= array.indices

CodePudding user response:

val list = arrayOf(arrayOf(1, 2, 3), arrayOf(4, 5, 6))

val result = list.first().mapIndexed { 
  index, _ -> list.sumOf { it[index] }.div(list.size.toDouble())
}

println(result)   // [2.5, 3.5, 4.5]

This would also work for any number of sub-arrays:

val list = arrayOf(arrayOf(1, 2, 3), arrayOf(4, 5, 6), arrayOf(7, 8, 9))
...
println(result)   // [4.0, 5.0, 6.0]

CodePudding user response:

Assuming all rows contain equal number of columns, you can do it this way:

val array = listOf(listOf(1, 2, 3), listOf(4, 5, 6))
val columns = array.first().size
val meanArray = List(columns) { col -> array.map { it[col] }.average() }
println(meanArray)

try it yourself

Here List(columns) creates a list with number of elements equal to columns. Then for each column col array.map { it[col] } creates a list of elements in that column which is followed by a call to average() which just calculates the average of list elements.

  • Related