Back to Problems
## Reshape Matrix (easy)

#### Example

## Reshaping a Matrix

Matrix reshaping involves changing the shape of a matrix without altering its data. This is essential in many machine learning tasks where the input data needs to be formatted in a specific way.
For example, consider a matrix \(M\):
Original Matrix \(M\):
\[
M = \begin{pmatrix}
1 & 2 & 3 & 4 \\
5 & 6 & 7 & 8
\end{pmatrix}
\]
Reshaped Matrix \(M'\) with shape (4, 2):
\[
M' = \begin{pmatrix}
1 & 2 \\
3 & 4 \\
5 & 6 \\
7 & 8
\end{pmatrix}
\]
Ensure the total number of elements remains constant during reshaping.

Write a Python function that reshapes a given matrix into a specified shape.

Example: input: a = [[1,2,3,4],[5,6,7,8]], new_shape = (4, 2) output: [[1, 2], [3, 4], [5, 6], [7, 8]] reasoning: The given matrix is reshaped from 2x4 to 4x2.

import numpy as np def reshape_matrix(a: list[list[int|float]], new_shape: tuple[int|float]) -> list[list[int|float]]: return np.array(a).reshape(new_shape).tolist()

Output will be shown here.

Solution copied to clipboard!