RunMat
GitHub

View all functions

CategoryArray: Shape
GPUYes

reshape — Rearrange the dimensions of an array without changing its data.

reshape(A, newSize) returns the elements of A with a different dimensional layout while preserving column-major ordering. The total number of elements must remain unchanged.

How does the reshape function behave in MATLAB / RunMat?

  • Accepts either a size vector reshape(A, [m n …]) or individual dimensions reshape(A, m, n, …).
  • Exactly one dimension may be specified as []; RunMat infers its value from numel(A).
  • Dimensions must be nonnegative integers. Zero-sized dimensions are allowed when numel(A) == 0.
  • Works on numeric, logical, complex, string, char, GPU, and cell arrays (cell/char currently support up to 2-D).
  • Reshaping never copies data; it only reinterprets layout metadata.
  • Scalar inputs follow MATLAB semantics: reshape(5, 1, 1) yields the scalar 5, while larger shapes return dense arrays.

GPU behavior

When the input lives on the GPU, RunMat asks the active acceleration provider to apply the reshape hook so the backend can update its residency metadata. No data transfers or kernel launches are needed, so gpuArray inputs stay on the device. Providers that do not override the hook fall back to updating the tensor handle directly, which is sufficient for the in-process reference backend.

Examples of using reshape in MATLAB / RunMat

Reshaping a row vector into a matrix

A = 1:12;
B = reshape(A, [3, 4])

Expected output:

B =
    1     4     7    10
    2     5     8    11
    3     6     9    12

Using an automatically inferred dimension

A = 1:18;
B = reshape(A, 3, [])

Expected output:

size(B)  % => [3 6]

Reshaping into three dimensions

A = 1:24;
C = reshape(A, [2, 3, 4])

Expected output:

size(C)  % => [2 3 4]

Reshaping logical arrays preserves type

mask = logical([1 0 1 0 1 0]);
grid = reshape(mask, 2, 3)

Expected output:

grid =
     1     1     1
     0     0     0

Reshaping GPU data without gathering

G = gpuArray(1:1000);
H = reshape(G, 10, 100)

Handling zero-sized dimensions

E = reshape([], 0, 3)

Expected output:

size(E)  % => [0 3]

See also

size, ndims, numel, gpuArray, gather

Source & Feedback