Tutorial

How to Get the Number of Dimensions of a Matrix in MATLAB

The function ndims returns the number of dimensions of a matrix.

Preparation

Create three matrices using the following code:

A = 1:5;
B = [1, 2, 3; 4, 5, 6];
C = ones(2,3,2);

Syntax

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.

Dimensions: Group of properties that are necessary and sufficient to determine uniquely each element of a system.
% Number of dimensions of the row vector A
nDimsA = ndims(A);
% Number of dimensions of the 2D matrix B
nDimsB = ndims(B);
% Number of dimensions of the 3D matrix C
nDimsC = ndims(C);

Note: Row vectors and column vectors are of size 1-by-N and N-by-1, respectively, therefore they have two dimensions.

Further reading

I recommend the following books to learn more on matrix manipulation in MATLAB.

  1. MATLAB: A Practical Introduction to Programming and Problem Solving (4th Edition)

    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.

  2. 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.

doc ndims;

Source code

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.

Share

Your friends may need this knowledge to complete a task. Share this tutorial.