Programming Previous page   Next Page

Specialized Matrix Functions

MATLAB has a number of functions that create different kinds of matrices. Some create specialized matrices like the Hankel or Vandermonde matrix. The functions shown in the table below create matrices for more general use.

Function
Description
ones
Create a matrix or array of all ones.
zeros
Create a matrix or array of all zeros.
eye
Create a matrix with ones on the diagonal and zeros elsewhere.
accumarray
Distribute elements of an input matrix to specified locations in an output matrix, also allowing for accumulation.
diag
Create a diagonal matrix from a vector.
magic
Create a square matrix with rows, columns, and diagonals that add up to the same number.
rand
Create a matrix or array of uniformly distributed random numbers.
randn
Create a matrix or array of normally distributed random numbers and arrays.
randperm
Create a vector (1-by-n matrix) containing a random permutation of the specified integers.

Most of these functions return matrices of type double (double-precision floating point). However, you can easily build basic arrays of any numeric type using the ones, zeros, and eye functions.

To do this, specify the MATLAB class name as the last argument:

Examples

Here are some examples of how you can use these functions.

Creating a Magic Square Matrix.   A magic square is a matrix in which the sum of the elements in each column, or each row, or each main diagonal is the same. To create a 5-by-5 magic square matrix, use the magic function as shown.

Note that the elements of each row, each column, and each main diagonal add up to the same value: 65.

Creating a Random Matrix.   The rand function creates a matrix or array with elements uniformly distributed between zero and one. This example multiplies each element by 20:

Creating a Diagonal Matrix.   Use diag to create a diagonal matrix from a vector. You can place the vector along the main diagonal of the matrix, or on a diagonal that is above or below the main one, as shown here. The -1 input places the vector one row below the main diagonal:


Previous page  Creating and Concatenating Matrices Concatenating Matrices Next page

© 1994-2005 The MathWorks, Inc.