Create two matrices using the following code:
A = [1, 2, 3; 4, 5, 6]; B = ones(2,3,2);
A = 1 2 3 4 5 6
B(:,:,1) = 1 1 1 1 1 1 B(:,:,2) = 1 1 1 1 1 1
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);
sizeA = 2 3
% Size of matrix B sizeB = size(B);
sizeB = 2 3 2
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.
% Number of planes in B numPlanesB = size(B,3);
numPlanesB = 2
[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);
numRowsA = 2
numColsA = 3
% Insufficient output arguments (B is a 3D matrix) [numRowsB,product] = size(B);
numRowsB = 2
product = 6
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 explains 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 size of a matrix in MATLAB. The source code developed in this tutorial is available at this page.