3.4 Reshape, view, copy, and transpose
Explanation
reshape changes how data are indexed as an array with a different shape. It does not necessarily sort, transpose, or copy the data. Often it is better to think of reshape as changing the view of a data buffer.
A copy creates a new owned data object. A view refers to existing data with a different way to access it. A transpose swaps axes mathematically; it is not the same idea as reshape.
For tensor libraries, reshape, view, and transpose are often changes to tensor metadata: shape, strides, axis order, or ownership of the underlying buffer. The exact behavior depends on the operation, so always check whether data are copied or shared.
The row-major or column-major convention also matters: the same buffer can give a different reshaped view depending on how linear memory is mapped to array indices. Which convention applies depends on the language and array library.
For N-dimensional arrays, use the fastest-varying index rule from memory layout: column-major order changes the leftmost index fastest, while row-major order changes the rightmost index fastest.
Things to look up
reshape- View
- Copy
- Transpose
- Data buffer
- Owned buffer
- Tensor metadata
- Stride
- Row-major order
- Column-major order
- Fastest-varying index
Exercise
Suppose the data buffer is [1, 2, 3, 4, 5, 6].
- Draw one possible
2 x 3reshaped view using column-major order. - Draw one possible
3 x 2reshaped view using column-major order. - Draw one possible
2 x 3reshaped view using row-major order, and compare it with the first answer. - Explain why reshape is not the same as sorting.
- Explain why reshape is not the same as transpose.
Notes for the exercise
- State whether data are copied or shared if you know the operation.
- Do not assume a new array is always allocated.
- Do not confuse shape change with element reordering.
- For N-dimensional data, write down which index changes fastest before translating or optimizing array code.
- In Rust, check the tensor or array crate documentation to learn whether
reshape,view,clone, or transpose-like operations share an owned buffer or allocate a new one.