Next  |  Prev  |  Top  |  JOS Index  |  JOS Pubs  |  JOS Home  |  Search

FOR, WHILE and IF

The FOR clause allows statements to be repeated a specific number of times. The general form is

   FOR variable = expr,  statement, ..., statement, END
The END and the comma before it may be omitted. In general, the expression may be a matrix, in which case the columns are stored one at a time in the variable and the following statements, up to the END or the end of the line, are executed. The expression is often of the form j:k, and its "columns" are simply the scalars from j to k. Some examples (assume n has already been assigned a value):
   for i = 1:n, for j = 1:n, A(i,j) = 1/(i+j-1);
generates the Hilbert matrix.
   for j = 2:n-1, for i = j:n-1, ...
      A(i,j) = 0; end; A(j,j) = j; end; A
changes all but the "outer edge" of the lower triangle and then prints the final matrix.
   for h = 1.0: -0.1: -1.0, (<h, cos(pi*h)>)
prints a table of cosines.
   <X,D> = EIG(A); for v = X, v, A*v
displays eigenvectors, one at a time.

The WHILE clause allows statements to be repeated an indefinite number of times. The general form is

   WHILE expr relop expr,   statement,..., statement, END
where relop is =, <, >, <=, >=, or <> (not equal) . The statements are repeatedly executed as long as the indicated comparison between the real parts of the first components of the two expressions is true. Here are two examples. (Exercise for the reader: What do these segments do?)
   eps = 1;
   while 1 + eps > 1, eps = eps/2;
   eps = 2*eps

   E = 0*A;  F = E + EYE; n = 1;
   while NORM(E+F-E,1) > 0, E = E + F; F = A*F/n; n = n + 1;
   E

The IF clause allows conditional execution of statements. The general form is

   IF expr relop expr,   statement, ..., statement,
      ELSE statement, ..., statement
The first group of statements are executed if the relation is true and the second group are executed if the relation is false. The ELSE and the statements following it may be omitted. For example,
   if abs(i-j) = 2, A(i,j) = 0;


Next  |  Prev  |  Top  |  JOS Index  |  JOS Pubs  |  JOS Home  |  Search