1
@c Copyright (C) 1996, 1997, 1999, 2000, 2002, 2003, 2004, 2007 John W. Eaton
3
@c This file is part of Octave.
5
@c Octave is free software; you can redistribute it and/or modify it
6
@c under the terms of the GNU General Public License as published by the
7
@c Free Software Foundation; either version 3 of the License, or (at
8
@c your option) any later version.
10
@c Octave is distributed in the hope that it will be useful, but WITHOUT
11
@c ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12
@c FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15
@c You should have received a copy of the GNU General Public License
16
@c along with Octave; see the file COPYING. If not, see
17
@c <http://www.gnu.org/licenses/>.
23
Statements may be a simple constant expression or a complicated list of
24
nested loops and conditional statements.
26
@dfn{Control statements} such as @code{if}, @code{while}, and so on
27
control the flow of execution in Octave programs. All the control
28
statements start with special keywords such as @code{if} and
29
@code{while}, to distinguish them from simple expressions.
30
Many control statements contain other statements; for example, the
31
@code{if} statement contains another statement which may or may not be
34
@cindex @code{end} statement
35
Each control statement has a corresponding @dfn{end} statement that
36
marks the end of the end of the control statement. For example, the
37
keyword @code{endif} marks the end of an @code{if} statement, and
38
@code{endwhile} marks the end of a @code{while} statement. You can use
39
the keyword @code{end} anywhere a more specific end keyword is expected,
40
but using the more specific keywords is preferred because if you use
41
them, Octave is able to provide better diagnostics for mismatched or
44
The list of statements contained between keywords like @code{if} or
45
@code{while} and the corresponding end statement is called the
46
@dfn{body} of a control statement.
50
* The switch Statement::
51
* The while Statement::
52
* The do-until Statement::
54
* The break Statement::
55
* The continue Statement::
56
* The unwind_protect Statement::
58
* Continuation Lines::
61
@node The if Statement
62
@section The @code{if} Statement
63
@cindex @code{if} statement
64
@cindex @code{else} statement
65
@cindex @code{elseif} statement
66
@cindex @code{endif} statement
68
The @code{if} statement is Octave's decision-making statement. There
69
are three basic forms of an @code{if} statement. In its simplest form,
81
@var{condition} is an expression that controls what the rest of the
82
statement will do. The @var{then-body} is executed only if
83
@var{condition} is true.
85
The condition in an @code{if} statement is considered true if its value
86
is non-zero, and false if its value is zero. If the value of the
87
conditional expression in an @code{if} statement is a vector or a
88
matrix, it is considered true only if it is non-empty and @emph{all}
89
of the elements are non-zero.
91
The second form of an if statement looks like this:
104
If @var{condition} is true, @var{then-body} is executed; otherwise,
105
@var{else-body} is executed.
112
printf ("x is even\n");
114
printf ("x is odd\n");
119
In this example, if the expression @code{rem (x, 2) == 0} is true (that
120
is, the value of @code{x} is divisible by 2), then the first
121
@code{printf} statement is evaluated, otherwise the second @code{printf}
122
statement is evaluated.
124
The third and most general form of the @code{if} statement allows
125
multiple decisions to be combined in a single statement. It looks like
132
elseif (@var{condition})
141
Any number of @code{elseif} clauses may appear. Each condition is
142
tested in turn, and if one is found to be true, its corresponding
143
@var{body} is executed. If none of the conditions are true and the
144
@code{else} clause is present, its body is executed. Only one
145
@code{else} clause may appear, and it must be the last part of the
148
In the following example, if the first condition is true (that is, the
149
value of @code{x} is divisible by 2), then the first @code{printf}
150
statement is executed. If it is false, then the second condition is
151
tested, and if it is true (that is, the value of @code{x} is divisible
152
by 3), then the second @code{printf} statement is executed. Otherwise,
153
the third @code{printf} statement is performed.
158
printf ("x is even\n");
159
elseif (rem (x, 3) == 0)
160
printf ("x is odd and divisible by 3\n");
162
printf ("x is odd\n");
167
Note that the @code{elseif} keyword must not be spelled @code{else if},
168
as is allowed in Fortran. If it is, the space between the @code{else}
169
and @code{if} will tell Octave to treat this as a new @code{if}
170
statement within another @code{if} statement's @code{else} clause. For
171
example, if you write
184
Octave will expect additional input to complete the first @code{if}
185
statement. If you are using Octave interactively, it will continue to
186
prompt you for additional input. If Octave is reading this input from a
187
file, it may complain about missing or mismatched @code{end} statements,
188
or, if you have not used the more specific @code{end} statements
189
(@code{endif}, @code{endfor}, etc.), it may simply produce incorrect
190
results, without producing any warning messages.
192
It is much easier to see the error if we rewrite the statements above
207
using the indentation to show how Octave groups the statements.
208
@xref{Functions and Scripts}.
210
@node The switch Statement
211
@section The @code{switch} Statement
212
@cindex @code{switch} statement
213
@cindex @code{case} statement
214
@cindex @code{otherwise} statement
215
@cindex @code{endswitch} statement
217
It is very common to take different actions depending on the value of
218
one variable. This is possible using the @code{if} statement in the
225
do_something_else ();
227
do_something_completely_different ();
232
This kind of code can however be very cumbersome to both write and
233
maintain. To overcome this problem Octave supports the @code{switch}
234
statement. Using this statement, the above example becomes
241
do_something_else ();
243
do_something_completely_different ();
248
This code makes the repetitive structure of the problem more explicit,
249
making the code easier to read, and hence maintain. Also, if the
250
variable @code{X} should change it's name, only one line would need
251
changing compared to one line per case when @code{if} statements are
254
The general form of the @code{switch} statement is
258
switch @var{expression}
272
where @var{label} can be any expression. However, duplicate
273
@var{label} values are not detected, and only the @var{command_list}
274
corresponding to the first match will be executed. For the
275
@code{switch} statement to be meaningful at least one
276
@code{case @var{label} @var{command_list}} clause must be present,
277
while the @code{otherwise @var{command_list}} clause is optional.
279
If @var{label} is a cell array the corresponding @var{command_list}
280
is executed if @emph{any} of the elements of the cell array match
281
@var{expression}. As an example, the following program will print
282
@samp{Variable is either 6 or 7}.
288
printf ("variable is either 6 or 7\n");
290
printf ("variable is neither 6 nor 7\n");
294
As with all other specific @code{end} keywords, @code{endswitch} may be
295
replaced by @code{end}, but you can get better diagnostics if you use
298
@c Strings can be matched
300
One advantage of using the @code{switch} statement compared to using
301
@code{if} statements is that the @var{label}s can be strings. If an
302
@code{if} statement is used it is @emph{not} possible to write
305
if (X == "a string") # This is NOT valid
309
since a character-to-character comparison between @code{X} and the
310
string will be made instead of evaluating if the strings are equal.
311
This special-case is handled by the @code{switch} statement, and it
312
is possible to write programs that look like this
323
* Notes for the C programmer::
326
@node Notes for the C programmer
327
@subsection Notes for the C programmer
329
The @code{switch} statement is also available in the widely used C
330
programming language. There are, however, some differences
331
between the statement in Octave and C
335
Cases are exclusive, so they don't `fall through' as do the cases
336
in the @code{switch} statement of the C language.
339
The @var{command_list} elements are not optional. Making the list
340
optional would have meant requiring a separator between the label and
341
the command list. Otherwise, things like
352
would produce surprising results, as would
365
particularly for C programmers. If @code{doit()} should be executed if
366
@var{foo} is either @code{1} or @code{2}, the above code should be
367
written with a cell array like this
379
@node The while Statement
380
@section The @code{while} Statement
381
@cindex @code{while} statement
382
@cindex @code{endwhile} statement
384
@cindex body of a loop
386
In programming, a @dfn{loop} means a part of a program that is (or at least can
387
be) executed two or more times in succession.
389
The @code{while} statement is the simplest looping statement in Octave.
390
It repeatedly executes a statement as long as a condition is true. As
391
with the condition in an @code{if} statement, the condition in a
392
@code{while} statement is considered true if its value is non-zero, and
393
false if its value is zero. If the value of the conditional expression
394
in a @code{while} statement is a vector or a matrix, it is considered
395
true only if it is non-empty and @emph{all} of the elements are non-zero.
397
Octave's @code{while} statement looks like this:
401
while (@var{condition})
408
Here @var{body} is a statement or list of statements that we call the
409
@dfn{body} of the loop, and @var{condition} is an expression that
410
controls how long the loop keeps running.
412
The first thing the @code{while} statement does is test @var{condition}.
413
If @var{condition} is true, it executes the statement @var{body}. After
414
@var{body} has been executed, @var{condition} is tested again, and if it
415
is still true, @var{body} is executed again. This process repeats until
416
@var{condition} is no longer true. If @var{condition} is initially
417
false, the body of the loop is never executed.
419
This example creates a variable @code{fib} that contains the first ten
420
elements of the Fibonacci sequence.
427
fib (i) = fib (i-1) + fib (i-2);
434
Here the body of the loop contains two statements.
436
The loop works like this: first, the value of @code{i} is set to 3.
437
Then, the @code{while} tests whether @code{i} is less than or equal to
438
10. This is the case when @code{i} equals 3, so the value of the
439
@code{i}-th element of @code{fib} is set to the sum of the previous two
440
values in the sequence. Then the @code{i++} increments the value of
441
@code{i} and the loop repeats. The loop terminates when @code{i}
444
A newline is not required between the condition and the
445
body; but using one makes the program clearer unless the body is very
448
@node The do-until Statement
449
@section The @code{do-until} Statement
450
@cindex @code{do-until} statement
452
The @code{do-until} statement is similar to the @code{while} statement,
453
except that it repeatedly executes a statement until a condition becomes
454
true, and the test of the condition is at the end of the loop, so the
455
body of the loop is always executed at least once. As with the
456
condition in an @code{if} statement, the condition in a @code{do-until}
457
statement is considered true if its value is non-zero, and false if its
458
value is zero. If the value of the conditional expression in a
459
@code{do-until} statement is a vector or a matrix, it is considered
460
true only if it is non-empty and @emph{all} of the elements are non-zero.
462
Octave's @code{do-until} statement looks like this:
468
until (@var{condition})
473
Here @var{body} is a statement or list of statements that we call the
474
@dfn{body} of the loop, and @var{condition} is an expression that
475
controls how long the loop keeps running.
477
This example creates a variable @code{fib} that contains the first ten
478
elements of the Fibonacci sequence.
486
fib (i) = fib (i-1) + fib (i-2);
491
A newline is not required between the @code{do} keyword and the
492
body; but using one makes the program clearer unless the body is very
495
@node The for Statement
496
@section The @code{for} Statement
497
@cindex @code{for} statement
498
@cindex @code{endfor} statement
500
The @code{for} statement makes it more convenient to count iterations of a
501
loop. The general form of the @code{for} statement looks like this:
505
for @var{var} = @var{expression}
512
where @var{body} stands for any statement or list of statements,
513
@var{expression} is any valid expression, and @var{var} may take several
514
forms. Usually it is a simple variable name or an indexed variable. If
515
the value of @var{expression} is a structure, @var{var} may also be a
516
vector with two elements. @xref{Looping Over Structure Elements}, below.
518
The assignment expression in the @code{for} statement works a bit
519
differently than Octave's normal assignment statement. Instead of
520
assigning the complete result of the expression, it assigns each column
521
of the expression to @var{var} in turn. If @var{expression} is a range,
522
a row vector, or a scalar, the value of @var{var} will be a scalar each
523
time the loop body is executed. If @var{var} is a column vector or a
524
matrix, @var{var} will be a column vector each time the loop body is
527
The following example shows another way to create a vector containing
528
the first ten elements of the Fibonacci sequence, this time using the
529
@code{for} statement:
535
fib (i) = fib (i-1) + fib (i-2);
541
This code works by first evaluating the expression @code{3:10}, to
542
produce a range of values from 3 to 10 inclusive. Then the variable
543
@code{i} is assigned the first element of the range and the body of the
544
loop is executed once. When the end of the loop body is reached, the
545
next value in the range is assigned to the variable @code{i}, and the
546
loop body is executed again. This process continues until there are no
547
more elements to assign.
549
Within Octave is it also possible to iterate over matrices or cell arrays
550
using the @code{for} statement. For example consider
554
disp("Loop over a matrix")
558
disp("Loop over a cell array")
559
for i = @{1,"two";"three",4@}
566
In this case the variable @code{i} takes on the value of the columns of
567
the matrix or cell matrix. So the first loop iterates twice, producing
568
two column vectors @code{[1;2]}, followed by @code{[3;4]}, and likewise
569
for the loop over the cell array. This can be extended to loops over
570
multidimensional arrays. For example
574
a = [1,3;2,4]; b = cat(3, a, 2*a);
582
In the above case, the multidimensional matrix @var{c} is reshaped to a
583
two dimensional matrix as @code{reshape (c, rows(c),
584
prod(size(c)(2:end)))} and then the same behavior as a loop over a two
585
dimensional matrix is produced.
587
Although it is possible to rewrite all @code{for} loops as @code{while}
588
loops, the Octave language has both statements because often a
589
@code{for} loop is both less work to type and more natural to think of.
590
Counting the number of iterations is very common in loops and it can be
591
easier to think of this counting as part of looping rather than as
592
something to do inside the loop.
595
* Looping Over Structure Elements::
598
@node Looping Over Structure Elements
599
@subsection Looping Over Structure Elements
600
@cindex structure elements, looping over
601
@cindex looping over structure elements
603
A special form of the @code{for} statement allows you to loop over all
604
the elements of a structure:
608
for [ @var{val}, @var{key} ] = @var{expression}
615
In this form of the @code{for} statement, the value of @var{expression}
616
must be a structure. If it is, @var{key} and @var{val} are set to the
617
name of the element and the corresponding value in turn, until there are
618
no more elements. For example,
639
@print{} val = string
643
The elements are not accessed in any particular order. If you need to
644
cycle through the list in a particular way, you will have to use the
645
function @code{fieldnames} and sort the list yourself.
647
The @var{key} variable may also be omitted. If it is, the brackets are
648
also optional. This is useful for cycling through the values of all the
649
structure elements when the names of the elements do not need to be
652
@node The break Statement
653
@section The @code{break} Statement
654
@cindex @code{break} statement
656
The @code{break} statement jumps out of the innermost @code{for} or
657
@code{while} loop that encloses it. The @code{break} statement may only
658
be used within the body of a loop. The following example finds the
659
smallest divisor of a given integer, and also identifies prime numbers:
665
while (div*div <= num)
666
if (rem (num, div) == 0)
671
if (rem (num, div) == 0)
672
printf ("Smallest divisor of %d is %d\n", num, div)
674
printf ("%d is prime\n", num);
679
When the remainder is zero in the first @code{while} statement, Octave
680
immediately @dfn{breaks out} of the loop. This means that Octave
681
proceeds immediately to the statement following the loop and continues
682
processing. (This is very different from the @code{exit} statement
683
which stops the entire Octave program.)
685
Here is another program equivalent to the previous one. It illustrates
686
how the @var{condition} of a @code{while} statement could just as well
687
be replaced with a @code{break} inside an @code{if}:
694
if (rem (num, div) == 0)
695
printf ("Smallest divisor of %d is %d\n", num, div);
700
printf ("%d is prime\n", num);
707
@node The continue Statement
708
@section The @code{continue} Statement
709
@cindex @code{continue} statement
711
The @code{continue} statement, like @code{break}, is used only inside
712
@code{for} or @code{while} loops. It skips over the rest of the loop
713
body, causing the next cycle around the loop to begin immediately.
714
Contrast this with @code{break}, which jumps out of the loop altogether.
719
# print elements of a vector of random
720
# integers that are even.
722
# first, create a row vector of 10 random
723
# integers with values between 0 and 100:
725
vec = round (rand (1, 10) * 100);
727
# print what we're interested in:
738
If one of the elements of @var{vec} is an odd number, this example skips
739
the print statement for that element, and continues back to the first
740
statement in the loop.
742
This is not a practical example of the @code{continue} statement, but it
743
should give you a clear understanding of how it works. Normally, one
744
would probably write the loop like this:
756
@node The unwind_protect Statement
757
@section The @code{unwind_protect} Statement
758
@cindex @code{unwind_protect} statement
759
@cindex @code{unwind_protect_cleanup}
760
@cindex @code{end_unwind_protect}
762
Octave supports a limited form of exception handling modelled after the
763
unwind-protect form of Lisp.
765
The general form of an @code{unwind_protect} block looks like this:
771
unwind_protect_cleanup
778
where @var{body} and @var{cleanup} are both optional and may contain any
779
Octave expressions or commands. The statements in @var{cleanup} are
780
guaranteed to be executed regardless of how control exits @var{body}.
782
This is useful to protect temporary changes to global variables from
783
possible errors. For example, the following code will always restore
784
the original value of the global variable @code{frobnositcate}
785
even if an error occurs while performing the indexing operation.
789
save_frobnosticate = frobnosticate;
791
frobnosticate = true;
793
unwind_protect_cleanup
794
frobnosticate = save_frobnosticate;
800
Without @code{unwind_protect}, the value of @var{frobnosticate}
801
would not be restored if an error occurs while performing the indexing
802
operation because evaluation would stop at the point of the error and
803
the statement to restore the value would not be executed.
805
@node The try Statement
806
@section The @code{try} Statement
807
@cindex @code{try} statement
809
@cindex @code{end_try_catch}
811
In addition to unwind_protect, Octave supports another limited form of
814
The general form of a @code{try} block looks like this:
827
where @var{body} and @var{cleanup} are both optional and may contain any
828
Octave expressions or commands. The statements in @var{cleanup} are
829
only executed if an error occurs in @var{body}.
831
No warnings or error messages are printed while @var{body} is
832
executing. If an error does occur during the execution of @var{body},
833
@var{cleanup} can use the function @code{lasterr} to access the text
834
of the message that would have been printed. This is the same
835
as @code{eval (@var{try}, @var{catch})} but it is more efficient since
836
the commands do not need to be parsed each time the @var{try} and
837
@var{catch} statements are evaluated. @xref{Errors and Warnings}, for more
838
information about the @code{lasterr} function.
840
@cindex continuation lines
841
@cindex @code{...} continuation marker
842
@cindex @code{\} continuation marker
844
@node Continuation Lines
845
@section Continuation Lines
847
In the Octave language, most statements end with a newline character and
848
you must tell Octave to ignore the newline character in order to
849
continue a statement from one line to the next. Lines that end with the
850
characters @code{...} or @code{\} are joined with the following line
851
before they are divided into tokens by Octave's parser. For example,
856
x = long_variable_name ...
857
+ longer_variable_name \
863
form a single statement. The backslash character on the second line
864
above is interpreted as a continuation character, @emph{not} as a division
867
For continuation lines that do not occur inside string constants,
868
whitespace and comments may appear between the continuation marker and
869
the newline character. For example, the statement
873
x = long_variable_name ... # comment one
874
+ longer_variable_name \ # comment two
880
is equivalent to the one shown above. Inside string constants, the
881
continuation marker must appear at the end of the line just before the
884
Input that occurs inside parentheses can be continued to the next line
885
without having to use a continuation marker. For example, it is
886
possible to write statements like
890
if (fine_dining_destination == on_a_boat
891
|| fine_dining_destination == on_a_train)
892
seuss (i, will, not, eat, them, sam, i, am, i,
893
will, not, eat, green, eggs, and, ham);
899
without having to add to the clutter with continuation markers.