How to Find Size of Matrix in MATLAB: Syntax and Examples
In MATLAB, use the
size function to find the dimensions of a matrix. Calling size(A) returns the number of rows and columns of matrix A as a two-element vector.Syntax
The basic syntax to find the size of a matrix A is:
sz = size(A): Returns a vectorszwheresz(1)is the number of rows andsz(2)is the number of columns.[m, n] = size(A): Returns the number of rowsmand columnsnseparately.
matlab
sz = size(A); [m, n] = size(A);
Example
This example shows how to find the size of a 3x4 matrix and get the number of rows and columns separately.
matlab
A = [1 2 3 4; 5 6 7 8; 9 10 11 12]; sz = size(A); [m, n] = size(A);
Output
sz =
3 4
m =
3
n =
4
Common Pitfalls
One common mistake is to assume size(A) returns separate values instead of a vector. Another is mixing up rows and columns when indexing the output.
Wrong way:
rows = size(A) cols = size(A)
This assigns the full size vector to both variables.
Right way:
[rows, cols] = size(A)
matlab
A = [1 2; 3 4]; rows = size(A); % rows is [2 2], not number of rows cols = size(A); % cols is also [2 2] [rows, cols] = size(A); % Correct: rows=2, cols=2
Output
rows =
2 2
cols =
2 2
rows =
2
cols =
2
Quick Reference
Remember these tips when using size:
size(A)returns a vector with rows and columns.- Use
[m, n] = size(A)to get rows and columns separately. - For multi-dimensional arrays,
size(A, dim)returns size along dimensiondim.
Key Takeaways
Use
size(A) to get the dimensions of matrix A as a vector.Use
[m, n] = size(A) to get rows and columns separately.Avoid assigning
size(A) directly to separate variables without unpacking.For multi-dimensional arrays, specify the dimension with
size(A, dim).Remember that
size works for any array, not just 2D matrices.