How to Get the Size of a Matrix in MATLAB

The function size returns the size of a matrix in each dimension.


Create two matrices using the following code:

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

Syntax (I)

S = size(X) stores in the row vector S the size of matrix X in each dimension. The first value in S denotes number of rows, the second value denotes number of columns, the third value denotes number of planes, and so on.

% Size of matrix A
sizeA = size(A);
% Size of matrix B
sizeB = size(B);

Syntax (II)

d = size(X,dim) stores in the scalar d the size of X in the \(dim\)-th dimension. If dim is greater than the number of dimensions in X, the result is 1.

Order of dimensions: rows (1), columns (2), planes (3), and so on.
% Number of planes in B
numPlanesB = size(B,3);

Syntax (III)

[d1,d2,d3,…,dn] = size(X) stores in each output argument the size of X in the corresponding dimension.

If you provide more output arguments than dimensions in X, the exceeding arguments are set to 1. If you do not provide enough output arguments, the last one equals the product of the sizes of the remaining dimensions.

% Number of rows and columns in A
[numRowsA,numColsA] = size(A);
% Insufficient output arguments (B is a 3D matrix)
[numRowsB,product] = size(B);

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 Textbook Excellence Award. The second chapter explains 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 size;

Source code

I hope you have learned how to get the size of a matrix in MATLAB. The source code developed in this tutorial is available at this page.


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