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

$ls
cube.m dynamic.m script.m square.m

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

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

$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);
endfunction

$cat script.m
a=5.0

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

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

# ch = c obtained by using handle as arguments
handle=@cube;
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 http://www.gnu.org/software/octave/doc/interpreter/Function-Handles-Inline-Functions-and-Anonymous-Functions.html

2) http://rosettacode.org/wiki/Higher-order_functions 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.

Followers