Search This Blog

Wednesday, April 11, 2007

executing octave scripts

Using Octave 3.0.1, bash 4.1.5(1)-release on Debian Squeeze (stable)
$cat even_odd.m
# prevent Octave from thinking that this is a function file
clear;

function even_odd1(m)
# use bitand instead of mod to figure out if a number is odd or even
# if (mod(m, 2) == 1)
if (bitand(m,1))
printf("%d is odd\n", m)
else
printf("%d is even\n", m)
endif
endfunction

n = 25
even_odd1(n)
n = 30
even_odd1(n)
The above octave script can be run
1. Directly at the command line by doing
$octave -qf even_odd.m
n = 25
25 is odd
n = 30
30 is even
2. Inside Octave by doing
$octave -qf
octave:1> even_odd
n = 25
25 is odd
n = 30
30 is even
octave:2> n
n = 30
The advantage of first method is that no interaction is necessary. Useful for well tested scripts. The advantage of second method is that variables can be accessed even after the script is executed. Useful while debugging.

3. Source the script inside Octave
$octave -qf
octave:1> source("./even_odd.m")
n = 25
25 is odd
n = 30
30 is even
This approach comes in handy if the name of the script contains any special characters (ex:- '-' hyphen) or if the script has to be called by its relative path name.

No comments:

Followers