Next: M-files Up: No Title Previous: Command line editing

Submatrices and colon notation

Vectors and submatrices are often used in MATLAB to achieve fairly complex data manipulation effects. Colon notation" (which is used both to generate vectors and reference submatrices) and subscripting by vectors are keys to efficient manipulation of these objects. Creative use of these features permits one to minimize the use of loops (which slows MATLAB) and to make code simple and readable. Special effort should be made to become familiar with them.

The expression 1:5 (met earlier in for statements) is actually the row vector [1 2 3 4 5]. The numbers need not be integers nor the increment one. For example,

 
0.2:0.2:1.2
gives [0.2, 0.4, 0.6, 0.8, 1.0, 1.2], and

 5:-1:1  gives   [5 4 3 2 1].
The following statements will, for example, generate a table of sines. Try it.
 
         x = [0.0:0.1:2.0]' ;    
         y = sin(x);    
         [x y]
Note that since sin operates entry-wise, it produces a vector y from the vector x.

The colon notation can be used to access submatrices of a matrix. For example,

A(1:4,3) is the column vector consisting of the first four entries of the third column of A .

A colon by itself denotes an entire row or column:

A(:,3) is the third column of A , and A(1:4,:) is the first four rows.

Arbitrary integral vectors can be used as subscripts:

A(:,[2 4]) contains as columns, columns 2 and 4 of A .

Such subscripting can be used on both sides of an assignment statement:

A(:,[2 4 5]) = B(:,1:3) replaces columns 2,4,5 of A

with the first three columns of B. Note that the entire altered matrix A is printed and assigned. Try it. Columns 2 and 4 of A can be multiplied on the right by the 2-by-2 matrix [1 2;3 4]:

 
A(:,[2,4]) = A(:,[2,4])*[1 2;3 4]
Once again, the entire altered matrix is printed and assigned.

If x is an n-vector, what is the effect of the statement x = x(n:-1:1)? Try it.

To appreciate the usefulness of these features, compare these MATLAB statements with a Pascal, FORTRAN, or C routine to effect the same.



Next: M-files Up: No Title Previous: Command line editing


ladi@
Wed Mar 13 19:15:55 MET 1996