If you're interested in functional programming, you might also want to checkout my second blog which i'm actively working on!!

Tuesday, October 25, 2011

Using higher order functions with Octave

I was working on implementing the sigmoid exercise from the MachineLearning class. The assignment stated the following requirement:'Your code should also work with vectors and matrices'. But I already sensed that this is calling for using higher order functions.

The sigmoid function basically is defined as

Now you could of course write some for loops each time you want to apply a function to each element of a matrix, it makes more sense to write a generic mapper function which takes two parameters: a matrix (or vector) and a function to be applied to each element of that matrix. This mapper function then instead returns a new matrix. First thing to do was checking if Octave supported higher order functions. It turns 'feval'comes to the rescue.

Now for demonstrating this works i wrote a simple function which doubles its argument:

Now from the command line:

As Davy Meers pointed out Octave also supports anonymous functions which are even more powerful.


  1. Did you try using the built-in per-element arithmetic operators?

    For example:

    sigmoid = 1 ./ (1 + e.^(-z))