function reshape
reshape(
m: number,
n: number,
flag?: 0 | 1,
): matrix

Reshape an array or matrix into a new matrix of given dimensions.

Rearranges elements of an array or matrix into a new shape while preserving order.

Examples

Reshape a row vector into a column vector

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(reshape([5, 6, 3], 3, 1), [[5], [6], [3]]);

Reshape a column vector into a row vector

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(reshape([5, 6, 3], 1, 3), [[5, 6, 3]]);

Reshape a 2x3 matrix into a 3x2 matrix (row-wise)

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(reshape([[-1, 3, -1], [4, 5, 9]], 3, 2), [[-1, 3], [-1, 4], [5, 9]]);

Reshape a 2x3 matrix into a 3x2 matrix (column-wise)

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(reshape([[-1, 3, -1], [4, 5, 9]], 3, 2, 1), [[-1, 4], [3, 5], [-1, 9]]);

Reshape into a single-column matrix

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(reshape([[-1, 3, -1], [4, 5, 9]], 6, 1), [[-1], [3], [-1], [4], [5], [9]]);

Reshape into a single-column matrix (column-wise)

import { assertEquals, assertThrows } from "jsr:@std/assert";

assertEquals(reshape([[-1, 3, -1], [4, 5, 9]], 6, 1, 1), [[-1], [4], [3], [5], [-1], [9]]);

Parameters

The array or matrix to reshape.

m: number

Number of rows for the new matrix.

n: number

Number of columns for the new matrix.

optional
flag: 0 | 1 = 0

Flag (0: row-wise, 1: column-wise). Defaults to 0.

Return Type

The reshaped matrix.

Throws

If dimensions are invalid or inconsistent.