Getting Started with MATLAB   Search    Help Desk 

Working with Matrices

This section introduces you to other ways of creating matrices.

Generating Matrices

MATLAB provides four functions that generate basic matrices:

zeros

All zeros

ones

All ones

rand

Uniformly distributed random elements

randn     

Normally distributed random elements

Some examples:

load

The load command reads binary files containing matrices generated by earlier MATLAB sessions, or reads text files containing numeric data. The text file should be organized as a rectangular table of numbers, separated by blanks, with one row per line, and an equal number of elements in each row. For example, outside of MATLAB, create a text file containing these four lines:

Store the file under the name magik.dat. Then the command

reads the file and creates a variable, magik, containing our example matrix.

M-Files

You can create your own matrices using M-files, which are text files containing MATLAB code. Just create a file containing the same statements you would type at the MATLAB command line. Save the file under a name that ends in .m.

NOTE
To access a text editor on a PC or Mac, choose Open or New from the File menu or press the appropriate button on the toolbar. To access a text editor under UNIX, use the ! symbol followed by whatever command you would ordinarily use at your operating system prompt.

For example, create a file containing these five lines:

Store the file under the name magik.m. Then the statement

reads the file and creates a variable, A, containing our example matrix.

Concatenation

Concatenation is the process of joining small matrices to make bigger ones. In fact, you made your first matrix by concatenating its individual elements. The pair of square brackets, [], is the concatenation operator. For an example, start with the 4-by-4 magic square, A, and form

The result is an 8-by-8 matrix, obtained by joining the four submatrices.

This matrix is half way to being another magic square. Its elements are a rearrangement of the integers 1:64. Its column sums are the correct value for an 8-by-8 magic square.

But its row sums, sum(B')', are not all the same. Further manipulation is necessary to make this a valid 8-by-8 magic square.

Deleting Rows and Columns

You can delete rows and columns from a matrix using just a pair of square brackets. Start with

Then, to delete the second column of X, use

This changes X to

If you delete a single element from a matrix, the result isn't a matrix anymore. So, expressions like

result in an error. However, using a single subscript deletes a single element, or sequence of elements, and reshapes the remaining elements into a row vector. So

results in



[ Previous | Help Desk | Next ]