Skip to content

← JAX Foundations step 5 of 25

Easy Primitives

Functional Update with .at[].set()

Jump to the task

Replace entries and keep the original array

Ordinary JAX arrays do not support item assignment. Instead, arr.at[indices].set(values) returns an updated array value. Keep that result; the original array remains unchanged.

import jax.numpy as jnp

arr = jnp.array([1., 2., 3.])
updated = arr.at[1].set(99.)
# arr:     [1., 2., 3.]
# updated: [1., 99., 3.]

Rebinding arr to the result is also valid. It changes what the Python name refers to, not the old array value. Compiler buffer reuse is an implementation detail and does not let you observe mutation of the original ordinary array.

Pair each position with a replacement

For arr = [10, 20, 30, 40], indices = [0, 3] and values = [7, 8], set position 0 to 7 and position 3 to 8. The result is [7, 20, 30, 8]. This replaces entries rather than adding contributions.

The exercise supplies whole-number indices as float arrays. Convert them to int32 before indexing. Casting is an interface conversion, not validation: a fractional number would be truncated and would not identify the intended position reliably.

Conflicting replacements need a defined policy

If several replacements target the same position, .set does not guarantee that the last input value wins on every backend. Do not infer a portable rule from the result on one machine. This exercise uses distinct indices so each destination has exactly one replacement. Use .add when the intended operation is to accumulate contributions; that changes the operation, not just its implementation.

Problem

Implement update_at_indices(arr, indices, values) with .at[].set().

Arr and values are one-dimensional finite float32 JAX arrays. Indices is a one-dimensional array of distinct, nonnegative whole numbers supplied as floats. Every index is representable as int32 and is less than arr.shape[0]. Values and indices have the same length.

Return a JAX array with arr's shape and dtype, replacing each listed position with its corresponding value. All other entries stay unchanged. Do not modify arr. Empty indices and values leave it unchanged; an empty arr is valid only with no updates.

Out-of-range indices are outside this task's contract. Do not rely on a Python IndexError to validate JAX scatter updates. The returned array represents the result regardless of any internal buffer optimization.