Multik 0.3.0 Help

Iterating over arrays

Overview

Iteration in Multik is element-wise by default. Use indices or multi-indices when you need coordinates along each axis.

Element-wise iteration

You can iterate an ndarray just like a Kotlin collection:

val a = mk.ndarray(mk[1, 2, 3]) for (value in a) { print("$value ") } // 1 2 3

Multik also provides forEach for concise iteration:

a.forEach { value -> println(value) }

Iteration walks the array in logical index order (the last axis changes fastest) and respects views/strides.

Iterating with indices (1D)

For one-dimensional arrays, use indices or forEachIndexed:

val v = mk.ndarray(mk[10, 20, 30]) for (i in v.indices) { println("v[$i] = ${v[i]}") } v.forEachIndexed { i, value -> println("$i -> $value") }

Iterating with multi-indices (ND)

For multidimensional arrays, multiIndices gives all index tuples. Each index is an IntArray that you can pass back into the array.

val m = mk.ndarray(mk[mk[1.5, 2.1, 3.0], mk[4.0, 5.0, 6.0]]) for (index in m.multiIndices) { print("${m[index]} ") } // 1.5 2.1 3.0 4.0 5.0 6.0

There is also a helper that combines iteration with indices:

m.forEachMultiIndexed { index, value -> println("${index.joinToString()} -> $value") }

Updating values in-place

NDArray is mutable, so you can update elements as you iterate:

val x = mk.ndarray(mk[mk[1, 2], mk[3, 4]]) for (index in x.multiIndices) { x[index] = x[index] * 2 } // [[2, 4], [6, 8]]

If you need an independent copy before modifying, use copy() or deepCopy().

19 February 2026