Friday, January 3, 2014

Functional Programming in Matlab

It is possible to write functional programming style loops with arrayfun.

Let's start with an lambda function example.

>> y = arrayfun(@(x) x^2,1:10)

y =
     1     4     9    16    25    36    49    64    81   100 


We can also use the function handle @ with custom functions.

testFun.m
function y = testFun(x)

% do something more interesting...
if x > 0.5,
    y = 1;
else,
    y = 0;
end

Code to execute
x = rand(10, 1); % 10 random numbers between 0 and 1
y = arrayfun(@testFun, x);

No comments:

Post a Comment