Runs any examples associated with the function 'name'. Examples are stored in the script file, or in a file with the same name but no extension somewhere on your path. To keep them separate from the usual script code, all lines are prefixed by
%!
. Each example is 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) %! %------------------------------------------------- %! % the figure window shows one cycle of a sine waveNote that the code is displayed before it is executed, so a simple comment at the end suffices. It is generally not necessary to use disp or printf within the demo.
Demos are run in a function environment with no access to external variables. This means that all demos in your function must use separate initialization code. Alternatively, you can combine your demos into one huge demo, with the code:
%! input("Press <enter> to continue: ","s");between the sections, but this is discouraged. Other techniques include using multiple plots by saying figure between each, or using subplot to put multiple plots in the same window.
Also, since demo evaluates inside a function context, you cannot define new functions inside a demo. Instead you will have to use
eval(example('function',n))
to see them. Because eval only evaluates one line, or one statement if the statement crosses multiple lines, you must wrap your demo in "if 1 <demo stuff> endif" with the 'if' on the same line as 'demo'. For example,%!demo if 1 %! function y=f(x) %! y=x; %! endfunction %! f(3) %! endif
The following code
t=0:0.01:2*pi; x = sin(t); plot(t,x) %------------------------------------------------- % the figure window shows one cycle of a sine wave
Produces the following figure
![]() |