Entering Matrices in MATLAB

MATLAB works with essentially only one kind of object - a rectangular numerical matrix with possibly complex entries; all variables represent matrices. In some situations, l-by-l matrices are interpreted as scalars and matrices with only one row or one column are interpreted as vectors.

Matrices can be introduced into MATLAB in several different ways:

For example, either of these statements:

     A = [1 2 3; 4 5 6; 7 8 9]

or

     A = [ 1 2 3
              4 5 6
              7 8 9 ]

creates the obvious 3-by-3 matrix and assigns it to a variable A. The elements within a row of a matrix may be separated by commas as well as a blank.

When listing a number in exponential form (e.g. 2.34e-9), you must avoid using blank spaces. Listing entries of a large matrix is best done in an M-file, where you can easily edit out errors.

For example, the built-in functions rand, magic, and hilb provide an easy way to create matrices with which to experiment. The command

 
        rand(n)
        resp. rand(m,n)

will create an n-by-n, resp. m-by-n, matrix with randomly generated entries;

        magic(n)

will create an integral n-by-n matrix which is a magic square (rows and columns have common sum);

        hilb(n)

will create the n-by-n Hilbert matrix, the king of ill-conditioned matrices (m and n denote, of course, positive integers). Matrices can also be generated with a for-loop (see section on "For, While, and If Loops).

You can reference individual matrix and vector entries with indices inside parentheses in the usual manner. For example, A(2,3) denotes the entry in the second row, third column of matrix A and X(3) denotes the third coordinate of vector X.


Other Matlab Hints

Click on an item listed below to access additional MATLAB-related hints.


Return to ACS home page.


Please send comments and suggestions to

consult@rpi.edu