Search This Blog

Monday, May 17, 2010

passing functions as arguments in octave

It is possible to pass functions as arguments to another function in Octave. Consider the following sample code

cube.m dynamic.m script.m square.m

$cat square.m
function [sq] = square(x)
sq = x**2;

$cat cube.m
function [cu] = cube(x)
cu = x**3;

$cat dynamic.m
function [ ret ] = dynamic (fh, x)
# fh is a function name passed as a string
# ex:- b = dynamic("cube", a);
# fh can also be a handle
# handle = @square;
# b = dynamic(handle, a);
ret = feval(fh, x);

$cat script.m

# bh = b obtained by using handle as arguments
bh = dynamic( handle, a)

# bs = b obtained by using strings as arguments
bs = dynamic("square", a)

# ch = c obtained by using handle as arguments
ch = dynamic( handle, a)

# cs = c obtained by using strings as arguments
cs = dynamic("cube", a)

Run the script.m in octave

$octave3.2 -qf script.m

a = 5
bh = 25
bs = 25
ch = 125
cs = 125

Tested using Debian Lenny (stable), Octave 3.2.4

Further Reading:
1) The section on "Function handles, Inline Functions, and Anonymous Functions" in the octave manual

2) explains how to do this kind of "calling functions from functions" in various programming languages

1 comment:

Vikram said...

Thanks. Was trying to get a function handle defined from a definition in a separate m file, apparently octave doesnt support that.