Lesson 11: 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 down 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 = [0.2, 0.4, 0.6, 0.8, 1.0, 1.2]
and
	5:-1:1 = [5 4 3 2 1]

The following statements will, for example, generate a table of sines.

	x = [0.0:0.1:2.0]';
	y = sin(x);
	[x y]
Try it! 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 4 rows of A
Arbitrary integral vectors can be used as subscripts:
	A(:,[2 4]) contains as columns, column 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.
Columns 2 and 4 of A can be multiplied on he 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(x:-1:1) ?
Give it a try and see the result for yourself.

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