Create three matrices using the following code:
A = 1:5; B = [1, 2, 3; 4, 5, 6]; C = ones(2,3,2);
A = 1 2 3 4 5
B = 1 2 3 4 5 6
C(:,:,1) = 1 1 1 1 1 1 C(:,:,2) = 1 1 1 1 1 1
n = ndims(A) stores in
n the number of dimensions of matrix
A. The number of dimensions of any matrix is always greater than or equal to 2.
% Number of dimensions of the row vector A nDimsA = ndims(A);
nDimsA = 2
% Number of dimensions of the 2D matrix B nDimsB = ndims(B);
nDimsB = 2
% Number of dimensions of the 3D matrix C nDimsC = ndims(C);
nDimsC = 3
Note: Row vectors and column vectors are of size 1-by-N and N-by-1, respectively, therefore they have two dimensions.
I recommend the following books to learn more on matrix manipulation in MATLAB.
This book was the winner of a 2017 Textbook Excellence Award. The second chapter is dedicated to matrix manipulation and includes topics like matrix creation and indexing, and how to perform a wide list of operations on matrices.
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
I hope you have learned how to get the number of dimensions of a matrix in MATLAB. The source code developed in this tutorial is available at this page.