Programming  Getting Information About a Matrix

This section explains how to get the following information about an existing matrix:

Dimensions of the Matrix

These functions return information about the shape and size of a matrix.

 Function Description `length` Return the length of the longest dimension. (The length of a matrix or array with any zero dimension is zero.) `ndims` Return the number of dimensions. `numel` Return the number of elements. `size` Return the length of each dimension.

The following examples show some simple ways to use these functions. Both use the 3-by-5 matrix `A` shown here:

• ```A = rand(5) * 10;
A(4:5, :) = []
A =
9.5013    7.6210    6.1543    4.0571    0.5789
2.3114    4.5647    7.9194    9.3547    3.5287
6.0684    0.1850    9.2181    9.1690    8.1317
```

Example Using numel

Using the `numel` function, find the average of all values in matrix `A`:

• ```sum(A(:))/numel(A)
ans =
5.8909
```

Example Using ndims, numel, and size

Using `ndims` and `size`, go through the matrix and find those values that are between 5 and 7, inclusive:

• ```if ndims(A) ~= 2
return
end

[rows cols] = size(A);
for m = 1:rows
for n = 1:cols
x = A(m, n);
if x >= 5 && x <= 7
disp(sprintf('A(%d, %d) = %5.2f', m, n, A(m,n)))
end
end
end
```

The code returns the following:

• ```A(1, 3) =  6.15
A(3, 1) =  6.07
``` Logical Indexing Data Types Used in the Matrix © 1994-2005 The MathWorks, Inc.