Build a NumPy submatrix from separate row and column index arrays with np.ix_, keeping the given order and any repeated indices. It tests how advanced indexing pairs index arrays, how open-mesh broadcasting forms a cross product, and whether the result is a view or a copy.
Given a 2-D NumPy array `a` and 1-D integer index arrays `row_idx` and `col_idx`, return the submatrix where entry `[i, j]` equals `a[row_idx[i], col_idx[j]]`.
Requirements:
- Return a new array of shape `(len(row_idx), len(col_idx))`.
- Select with `a[np.ix_(row_idx, col_idx)]`, which takes the cross product of the two index arrays. Chained indexing and element-wise fancy indexing do not meet this requirement.
- Preserve the given index order. Repeated indices are allowed.
For example:
```python
a = np.arange(12).reshape(3, 4)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
row_idx = [0, 2]
col_idx = [1, 3]
out = a[np.ix_(row_idx, col_idx)]
# [[ 1 3]
# [ 9 11]]
```
```hint Compare the shapes
Work out what `a[row_idx, col_idx]` returns for the example. Then ask which shapes the two index arrays would need for broadcasting to produce an `(m, n)` grid.
```
### Constraints & Assumptions
- `a` is 2-D. `row_idx` and `col_idx` are 1-D and may arrive as Python lists or NumPy arrays.
- Every index is valid for its axis, so no bounds checking is needed.
- Indices can repeat and need not be sorted.
### What a Strong Answer Covers
- Why indexing with two 1-D integer arrays pairs them position by position instead of forming a grid
- The shapes `np.ix_` returns and how broadcasting turns them into the cross product
- Whether the result is a view or a copy, and how to write values back into `a`
- How repeated, unsorted and empty index arrays behave
### Follow-up Questions
- How does `np.ix_` produce the cross product internally?
- Is the returned submatrix a view or a copy, and how would you write values back into `a` at those positions?
- How would you extend this selection to an N-dimensional array?
Overview: Build a NumPy submatrix from separate row and column index arrays with np.ix_, keeping the given order and any repeated indices. It tests how advanced indexing pairs index arrays, how open-mesh broadcasting forms a cross product, and whether the result is a view or a copy.
Given a 2-D NumPy array a and 1-D integer index arrays row_idx and col_idx, return the submatrix where entry [i, j] equals a[row_idx[i], col_idx[j]].
Requirements:
Return a new array of shape
(len(row_idx), len(col_idx))
.
Select with
a[np.ix_(row_idx, col_idx)]
, which takes the cross product of the two index arrays. Chained indexing and element-wise fancy indexing do not meet this requirement.
Preserve the given index order. Repeated indices are allowed.