How to Find Length of Array in MATLAB: Simple Guide
In MATLAB, you can find the length of an array using the
length() function, which returns the largest dimension size. For more detailed size info, use size() to get the length of each dimension.Syntax
The main functions to find array length in MATLAB are:
length(array): Returns the largest dimension size of the array.size(array): Returns a vector with the size of each dimension.numel(array): Returns the total number of elements in the array.
matlab
len = length(array);
sz = size(array);
total = numel(array);Example
This example shows how to find the length of a 1D and 2D array using length() and size().
matlab
array1 = [10, 20, 30, 40]; array2 = [1, 2, 3; 4, 5, 6]; len1 = length(array1); sz1 = size(array1); len2 = length(array2); sz2 = size(array2); disp(['Length of array1: ', num2str(len1)]) disp(['Size of array1: ', mat2str(sz1)]) disp(['Length of array2: ', num2str(len2)]) disp(['Size of array2: ', mat2str(sz2)])
Output
Length of array1: 4
Size of array1: [1 4]
Length of array2: 3
Size of array2: [2 3]
Common Pitfalls
One common mistake is assuming length() returns the number of elements in all cases. It only returns the largest dimension size, which can be misleading for multi-dimensional arrays.
For example, a 2x3 matrix has length 3 (largest dimension), but total elements are 6.
Use numel() to get the total number of elements.
matlab
A = [1, 2, 3; 4, 5, 6]; wrong = length(A); % returns 3 right = numel(A); % returns 6 fprintf('Wrong length: %d\n', wrong); fprintf('Total elements: %d\n', right);
Output
Wrong length: 3
Total elements: 6
Quick Reference
| Function | Description | Example Output |
|---|---|---|
| length(array) | Largest dimension size of array | length([1 2 3]) โ 3 |
| size(array) | Size of each dimension as vector | size([1 2; 3 4]) โ [2 2] |
| numel(array) | Total number of elements | numel([1 2; 3 4]) โ 4 |
Key Takeaways
Use
length() to get the largest dimension size of an array.Use
size() to get the size of each dimension separately.Use
numel() to find the total number of elements in the array.For multi-dimensional arrays,
length() may not reflect total elements.Always choose the function based on whether you want dimension size or total elements.