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 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(:,3) is the third column of A, and A(1:4,:) is the first 4 rows of AArbitrary integral vectors can be used as subscripts: A(:,[2 4]) contains as columns, column 2 and 4 of ASuch 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 = 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. |