How to Use reshape in MATLAB: Syntax and Examples
In MATLAB, use the
reshape function to change the size of an array without changing its data. The syntax is reshape(A, m, n), where A is the original array and m, n are the new dimensions. The total number of elements must remain the same.Syntax
The basic syntax of reshape is:
B = reshape(A, m, n): Reshapes arrayAinto anm-by-nmatrix.A: The original array (can be vector, matrix, or multidimensional).m, n: The new dimensions. The productm*nmust equal the number of elements inA.B: The reshaped array with the specified size.
You can also reshape into more dimensions, e.g., reshape(A, m, n, p).
matlab
B = reshape(A, m, n)
Example
This example shows how to reshape a 2x3 matrix into a 3x2 matrix. The data stays the same but the shape changes.
matlab
A = [1 2 3; 4 5 6]; B = reshape(A, 3, 2); disp(B);
Output
1 4
2 5
3 6
Common Pitfalls
Common mistakes when using reshape include:
- Trying to reshape to dimensions where the total number of elements does not match the original array.
- Confusing row-major and column-major order: MATLAB fills the reshaped array column-wise.
- Using
reshapeon non-numeric arrays without checking compatibility.
Example of wrong and right usage:
matlab
% Wrong: dimensions do not match number of elements A = 1:6; % This will cause an error because 2*4=8 elements needed but A has 6 % B = reshape(A, 2, 4); % Right: matching total elements B = reshape(A, 3, 2); disp(B);
Output
1 4
2 5
3 6
Quick Reference
| Function | Description |
|---|---|
| reshape(A, m, n) | Change array A to m-by-n matrix, total elements must match |
| reshape(A, m, n, p) | Change array A to m-by-n-by-p array |
| numel(A) | Returns number of elements in A, useful to check before reshape |
| size(A) | Returns size of each dimension of A |
Key Takeaways
Use reshape to change array dimensions without altering data order.
Ensure the new shape has the same total number of elements as the original array.
MATLAB fills reshaped arrays column-wise, not row-wise.
Use numel(A) to verify element count before reshaping.
Reshape works with vectors, matrices, and multidimensional arrays.