Getting Information About a 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:

rand('state', 0);     % Initialize random number generator
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

Classes Used in the Matrix

These functions test elements of a matrix for a specific data type.

Function

Description

isa

Detect if input is of a given data type.

iscell

Determine if input is a cell array.

iscellstr

Determine if input is a cell array of strings.

ischar

Determine if input is a character array.

isfloat

Determine if input is a floating-point array.

isinteger

Determine if input is an integer array.

islogical

Determine if input is a logical array.

isnumeric

Determine if input is a numeric array.

isreal

Determine if input is an array of real numbers.

isstruct

Determine if input is a MATLAB® structure array.

Example Using isnumeric and isreal

Pick out the real numeric elements from this vector:

A = [5+7i 8/7 4.23 39j pi 9-2i];

for m = 1:numel(A)
   if isnumeric(A(m)) && isreal(A(m))
      disp(A(m))
   end
end

The values returned are

    1.1429
    4.2300
    3.1416

Data Structures Used in the Matrix

These functions test elements of a matrix for a specific data structure.

Function

Description

isempty

Determine if input has any dimension with size zero.

isscalar

Determine if input is a 1-by-1 matrix.

issparse

Determine if input is a sparse matrix.

isvector

Determine if input is a 1-by-n or n-by-1 matrix.

  


 © 1984-2008- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS