Navigation

Operators and Keywords

Function List:

C++ API

: demo name
: demo name n
: demo ("name")
: demo ("name", n)

Run example code block n associated with the function name.

If n is not specified, all examples are run.

The preferred location for example code blocks is embedded within the script m-file immediately following the code that it exercises. Alternatively, the examples may be stored in a file with the same name but no extension located on Octave’s load path. To separate examples from regular script code all lines are prefixed by %!. Each example must also be introduced by the keyword "demo" flush left to the prefix with no intervening spaces. The remainder of the example can contain arbitrary Octave code. For example:

%!demo
%! t = 0:0.01:2*pi;
%! x = sin (t);
%! plot (t, x);
%! title ("one cycle of a sine wave");
%! #-------------------------------------------------
%! # the figure window shows one cycle of a sine wave

Note that the code is displayed before it is executed so that a simple comment at the end suffices for labeling what is being shown. For plots, labeling can also be done with title or text. It is generally not necessary to use disp or printf within the demo.

Demos are run in a stand-alone function environment with no access to external variables. This means that every demo must have separate initialization code. Alternatively, all demos can be combined into a single large demo with the code

%! input ("Press <enter> to continue: ", "s");

between the sections, but this usage is discouraged. Other techniques to avoid multiple initialization blocks include using multiple plots with a new figure command between each plot, or using subplot to put multiple plots in the same window.

Finally, because demo evaluates within a function context it is not possible to define new functions within the code. Anonymous functions make a good substitute in most instances. If function blocks must be used then the code eval (example ("function", n)) will allow Octave to see them. This has its own problems, however, as eval only evaluates one line or statement at a time. In this case the function declaration must be wrapped with "if 1 <demo stuff> endif" where "if" is on the same line as "demo". For example:

%!demo if 1
%!  function y = f(x)
%!    y = x;
%!  endfunction
%!  f(3)
%! endif

See also: rundemos, example, test.

Demonstration 1

The following code

 t = 0:0.01:2*pi;
 x = sin (t);
 plot (t, x);
 title ("one cycle of a sine wave");
 #-------------------------------------------------
 # the figure window shows one cycle of a sine wave

Produces the following figure

Figure 1

Package: octave