Month: October 2010

Vector multiplication with some delay and intelligence: anonymous functions in Matlab and Python

Posted on Updated on

So our postdoctural machine learner Mikkel N. Schmidt noted the inadequacies of programming languages. For the following code

> a = [1; 2]
> b = [1; 2]
> x = a'*b
> a = [3; 4]

he would like to have the ‘x’ updated with the new ‘a’ so the result would be ’11’. In vanilla Matlab and Python you end up with the old value of ‘x’ based on the initial computation: ‘5’.

Mikkel pointed to the programming language Haskell, where this functionality supposedly would be possible. I am not into this functional programming thing but I have noticed there is this ‘lambda’ word in the Python programming language, and it seems to get you some of the way:

from numpy import *
a = mat([1, 2]).T
b = mat([1, 2]).T
x = lambda: a.T * b
a = mat([3, 4]).T

Here the result will be ’11’, — or rather a 1-times-1 matrix: ‘matrix([[11]])’. You can avoid that complex type getting a scalar by using the array Numpy type:

from numpy import *
a = array([1, 2])
b = array([1, 2])
x = lambda: dot(a,b)
a = array([3, 4])

I noticed that it wont work with ‘x = (lambda: dot(a,b))()’: Then you dont need to write ‘x()’ only ‘x’, but that ‘x’ will be ‘5’. It is a scalar and not a function pointer.

In newer versions of Matlab you can do anonymous functions with the ‘@()’ construct:

a = [1; 2];
b = [1; 2];
x = @() a'*b;
a = [3; 4];

But you get the result ‘5’. This is not a bug but a feature of Matlab: Upon construction of the function handle Matlab captures the current value of variables that are not among the input arguments and it stores them throughout the lifetime of the function handle. I wonder if there is another way to do it. You could define a function in a separate file with global variables.