Skip to content

← Tensor Foundations step 5 of 7

Easy Framework

Tensor Indexing and Slicing

Select whole rows from a matrix, in the order requested. Each selected row keeps all its columns.

Your task

Implement select_rows(x, rows).

  • x is a two-dimensional tensor of shape (m, n).
  • rows is a Python list of valid, zero-based integer row positions in [0, m).
  • Return shape (len(rows), n), with x's dtype and device. Leave x unchanged.

For x=[[10, 11], [20, 21], [30, 31]] and rows=[2, 0, 2], return [[30, 31], [10, 11], [30, 31]]. Row 2 appears twice because it was requested twice. Do not sort or deduplicate the indices.

Selecting one row still produces a matrix of shape (1, n). An empty list produces shape (0, n): the result has no rows but keeps its column dimension. This task uses a list of row positions, rather than a contiguous slice or a boolean mask.

In PyTorch, use x[rows]. In JAX, convert the list explicitly to integer indices: x[jnp.array(rows, dtype=jnp.int32)]. The explicit dtype also handles an empty list, which would otherwise become a floating-point array.