Mercurial > hg > octave-nkf
comparison doc/interpreter/stmt.txi @ 6587:00fad3bad2a5
[project @ 2007-04-26 20:23:31 by dbateman]
author | dbateman |
---|---|
date | Thu, 26 Apr 2007 20:23:31 +0000 |
parents | 3ef1aa12f04c |
children | c18ed0e7ee41 |
comparison
equal
deleted
inserted
replaced
6586:e4ea529efab0 | 6587:00fad3bad2a5 |
---|---|
503 @code{i} is assigned the first element of the range and the body of the | 503 @code{i} is assigned the first element of the range and the body of the |
504 loop is executed once. When the end of the loop body is reached, the | 504 loop is executed once. When the end of the loop body is reached, the |
505 next value in the range is assigned to the variable @code{i}, and the | 505 next value in the range is assigned to the variable @code{i}, and the |
506 loop body is executed again. This process continues until there are no | 506 loop body is executed again. This process continues until there are no |
507 more elements to assign. | 507 more elements to assign. |
508 | |
509 Within Octave is it also possible to iterate over matrices or cell arrays | |
510 using the @code{for} statement. For example consider | |
511 | |
512 @example | |
513 @group | |
514 disp("Loop over a matrix") | |
515 for i = [1,3;2,4] | |
516 i | |
517 endfor | |
518 disp("Loop over a cell array") | |
519 for i = @{1,"two";"three",4@} | |
520 i | |
521 endfor | |
522 @end group | |
523 @end example | |
524 | |
525 @noindent | |
526 In this case the variable @code{i} takes on the value of the columns of | |
527 the matrix or cell matrix. So the first loop iterates twice, producing | |
528 two column vectors @code{[1;2]}, follwed by @code{[3;4]}, and likewise | |
529 for the loop over the cell array. This can be extended to loops over | |
530 multidimensional arrays. For example | |
531 | |
532 @example | |
533 @group | |
534 a = [1,3;2,4]; b = cat(3, a, 2*a); | |
535 for i = c | |
536 i | |
537 endfor | |
538 @end group | |
539 @end example | |
540 | |
541 @noindent | |
542 In the above case, the mulitdimensional matrix @var{c} is reshaped to a | |
543 two dimensional matrix as @code{reshape (c, rows(c), | |
544 prod(size(c)(2:end)))} and then the same behavior as a loop over a two | |
545 dimensional matrix is produced. | |
508 | 546 |
509 Although it is possible to rewrite all @code{for} loops as @code{while} | 547 Although it is possible to rewrite all @code{for} loops as @code{while} |
510 loops, the Octave language has both statements because often a | 548 loops, the Octave language has both statements because often a |
511 @code{for} loop is both less work to type and more natural to think of. | 549 @code{for} loop is both less work to type and more natural to think of. |
512 Counting the number of iterations is very common in loops and it can be | 550 Counting the number of iterations is very common in loops and it can be |