Create a matrix using the following code:
A = [1:6;7:12];
A = 1 2 3 4 5 6 7 8 9 10 11 12
B = reshape(A,sz) copies the elements in matrix
A to a new matrix
B of size
sz is normally a row vector and must contain at least two elements.
Bare processed in their linear form, so
B(i) = A(i).
% A as a 3-by-4 matrix resultExample1 = reshape(A,[3,4]);
resultExample1 = 1 8 4 11 7 3 10 6 2 9 5 12
% A as a 3-by-2-by-2 matrix resultExample2 = reshape(A,[3,2,2]);
resultExample2(:,:,1) = 1 8 7 3 2 9 resultExample2(:,:,2) = 4 11 10 6 5 12
B = reshape(A,sz1,…,szN) copies the elements in matrix
A to a new matrix
B of size determined by the comma-separated list
If a value in the list is
, MATLAB calculates the size of the corresponding dimension automatically. The list must have at least two elements and only one can be
% A as a 6-by-2 matrix resultExample3 = reshape(A,6,2);
resultExample3 = 1 4 7 10 2 5 8 11 3 6 9 12
% A as a 4-by-3 matrix resultExample4 = reshape(A,,3);
resultExample4 = 1 3 5 7 9 11 2 4 6 8 10 12
Note: In both syntaxes, the output size must guarantee that the number of elements in
B is equal.
I recommend the following books to learn more on matrix reshaping in MATLAB.
This book was the winner of a Textbook Excellence Award. The second chapter explains how to perform a wide list of operations on matrices, including matrix reshaping.
MATLAB for Engineers (5th Edition)
This excellent book is especially oriented to engineers and scientists who want to learn MATLAB programming. Matrix manipulation is explained in the fourth chapter.
I also recommend the following page in the MATLAB help documentation, and the other tutorials in this series.
- How to Get the Size of a Matrix in MATLAB
- How to Get the Number of Elements in a Matrix in MATLAB
- How to Get the Number of Dimensions of a Matrix in MATLAB
- How to Reshape a Matrix in MATLAB
- How to Delete Items From a Matrix in MATLAB
- How to Transpose a 2D Matrix in MATLAB
- How to Transpose a Multidimensional Matrix in MATLAB
- How to Reverse a 2D Matrix in MATLAB
- How to Reverse a Multidimensional Matrix in MATLAB
Create a row vector using the following code:
X = 1:16;
X so it has:
- Two rows and eight columns
- Eight rows and two columns
- Four rows and four columns
A possible solution could be:
% Clause 1 X = reshape(X,2,8); % Clause 2 X = reshape(X,8,2); % Clause 3 X = reshape(X,4,);
I hope you have learned how to reshape a matrix in MATLAB. The source code developed in this tutorial is available at this page.