Next: Matrix operationsarray Up: No Title Previous: Accessing MATLAB

# Entering matrices

MATLAB works with essentially only one kind of object-a rectangular numerical matrix with possibly complex entries; all variables represent matrices. In some situations, 1-by-1 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:

• Entered by an explicit list of elements,
• Generated by built-in statements and functions,
• Created in M-files (see sections 12 and 14 below),
• Loaded from external data files (see User's Guide).
For example, either of the statements
```
A = [1 2 3; 4 5 6; 7 8 9]```
and
```
A = [
1  2  3
4  5  6
7  8  9 ]```
creates the obvious 3-by-3 matrix and assigns it to a variable A . Try it. 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), blank spaces must be avoided. Listing entries of a large matrix is best done in an M-file, where errors can be easily edited away (see sections 12 and 14).

The built-in functions rand, magic, and hilb, for example, provide an easy way to create matrices with which to experiment. The command rand(n) will create an n x n matrix with randomly generated entries distributed uniformly between 0 and 1, while rand(m,n) will create an m x n one. magic(n) will create an integral n x n matrix which is a magic square (rows and columns have common sum); hilb(n) will create the n x 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 6 below).

Individual matrix and vector entries can be referenced 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. Try it. A matrix or a vector will only accept positive integers as indices.

Next: Matrix operationsarray Up: No Title Previous: Accessing MATLAB