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.

One thought on “Vector multiplication with some delay and intelligence: anonymous functions in Matlab and Python

    Mikkel N. Schmidt said:
    October 6, 2010 at 10:51 am

    In Matlab we could also writex = @() evalin(‘caller’,’a’)’*evalin(‘caller’,’b’);Not pretty, but it does the trick. What I would really like to have is a language where this is all natural and easy to read/write.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s