Loading content...
In numerical computing and data processing, matrix dimension restructuring is a fundamental operation that transforms a matrix from one shape to another while preserving the order and values of all elements. This operation is sometimes referred to as dimensional rearrangement or shape transformation.
Given a matrix A with dimensions n × m (containing n × m total elements) and a target shape (p, q), the restructuring operation rearranges the elements into a new matrix B with dimensions p × q. The elements are read from the original matrix in row-major order (left-to-right, top-to-bottom) and written into the new matrix following the same ordering convention.
Feasibility Condition: For restructuring to be valid, the total number of elements must remain constant. Mathematically, this means:
$$n \times m = p \times q$$
If this condition is not satisfied, the restructuring is impossible, and the operation should indicate failure by returning an empty result.
Element Mapping: When restructuring is possible, element at position (i, j) in the original matrix maps to a new position in the target matrix based on its linear index. The linear index k of an element is calculated as:
$$k = i \times m + j$$
In the restructured matrix, this element appears at position:
Your Task: Write a Python function that restructures a given matrix into the specified target dimensions. The function should:
matrix = [[1, 2, 3, 4], [5, 6, 7, 8]]
target_dimensions = (4, 2)[[1, 2], [3, 4], [5, 6], [7, 8]]The original matrix has dimensions 2×4 with 8 total elements. The target dimensions are 4×2, which also requires 8 elements (4 × 2 = 8).
The elements are read in row-major order: 1, 2, 3, 4, 5, 6, 7, 8
They are then filled into the new 4×2 structure: • Row 0: elements 0-1 → [1, 2] • Row 1: elements 2-3 → [3, 4] • Row 2: elements 4-5 → [5, 6] • Row 3: elements 6-7 → [7, 8]
The restructured matrix is [[1, 2], [3, 4], [5, 6], [7, 8]].
matrix = [[1, 2, 3], [4, 5, 6]]
target_dimensions = (3, 2)[[1, 2], [3, 4], [5, 6]]The original 2×3 matrix contains 6 elements. The target shape 3×2 also requires exactly 6 elements.
Elements in row-major order: 1, 2, 3, 4, 5, 6
Filling into 3×2 structure: • Row 0: [1, 2] • Row 1: [3, 4] • Row 2: [5, 6]
The restructuring successfully transforms the matrix from a wide format to a taller format.
matrix = [[1, 2], [3, 4]]
target_dimensions = (3, 3)[]The original 2×2 matrix contains 4 elements. However, the target shape 3×3 requires 9 elements (3 × 3 = 9).
Since 4 ≠ 9, it's impossible to restructure the matrix into the requested dimensions without either losing elements or creating undefined values.
The function returns an empty list [] to indicate that restructuring is not feasible.
Constraints