0
0
MATLABdata~5 mins

Reshaping arrays in MATLAB

Choose your learning style9 modes available
Introduction

Reshaping arrays lets you change the shape or size of your data without changing its values. It helps organize data in a way that fits your needs.

You have a list of numbers and want to turn it into a matrix with rows and columns.
You want to prepare data for a function that needs a specific shape.
You want to flatten a matrix into a single row or column.
You want to split a long list into smaller blocks for easier processing.
Syntax
MATLAB
reshapedArray = reshape(originalArray, newRowCount, newColumnCount);

The total number of elements must stay the same before and after reshaping.

You can reshape to more than 2 dimensions by adding more size arguments.

Examples
This turns a 1-by-6 row vector into a 2-by-3 matrix.
MATLAB
A = 1:6;
B = reshape(A, 2, 3);
This reshapes a 2-by-2 matrix into a 4-by-1 column vector.
MATLAB
A = [1 2; 3 4];
B = reshape(A, 4, 1);
This reshapes a 1-by-8 vector into a 3D array with size 2-by-2-by-2.
MATLAB
A = 1:8;
B = reshape(A, 2, 2, 2);
Reshape must keep the total number of elements the same.
MATLAB
A = 1:5;
% reshape(A, 2, 3) would cause an error because 5 elements can't fill 6 spots.
Sample Program

This program starts with a 1-by-12 row vector. It reshapes it into a 3-by-4 matrix, then reshapes it again into a 3D array with size 2-by-2-by-3. It prints the arrays before and after reshaping.

MATLAB
originalArray = 1:12;
disp('Original array:');
disp(originalArray);

reshapedArray = reshape(originalArray, 3, 4);
disp('Reshaped array (3 rows, 4 columns):');
disp(reshapedArray);

reshapedArray2 = reshape(originalArray, 2, 2, 3);
disp('Reshaped array into 3D (2x2x3):');
disp(reshapedArray2);
OutputSuccess
Important Notes

Reshape operation runs in O(1) time because it only changes how data is viewed, not the data itself.

Space complexity is O(1) extra space since no new data is created, just a new view.

A common mistake is trying to reshape to a size that doesn't match the total number of elements.

Use reshape when you want to reorganize data without changing values. Use other functions like transpose if you want to flip rows and columns.

Summary

Reshape changes the shape of an array without changing its data.

The total number of elements must stay the same before and after reshaping.

It works for vectors, matrices, and multi-dimensional arrays.