493: Undecipherable

-Blog-

-Projects-

-About me-

-RSS-

Matlab: if-statement in anonymous functions

Dennis Guse

UPDATE: The performance penalty is massive - MATLAB fails to optimize the code if anonymous functions or function handles are used. I got factor 20… But it works ;)

Today, I needed to write a function in Matlab as accessor to a matrix. I have a matrix which contain mulitple datastreams - one per row. The columns dimension is the time Because I don’t want to change the functions, which evaluate only a subset of provided streams, and I don’t want to copy and modify the matrix for every combination, I started to think about an accessor function. Furthermore the function should reveal the dimensions of the (not existing) data matrix. I ended up with anonymous functions, because these allow to access variables outside the anonymous function definition like:

1
2
3
  a=2 
  b=2 
  fun=@(x)(a*x+b) 

The advantage is that fun can use a and b, but the caller doesn’t necessarily know that they exist and are used by fun. With this knowledge the implementation of providing the correct data was straight forward. The next problem was, that in anonymous function you can’t use the if-statement. That’s pretty messy. I found a (solution)[http://www.mathworks.com/matlabcentral/newsreader/view_thread/147044] and adapted it.

1
2
3
4
5
6
7
8
9
%%Artificial if for use in anonymous functions
%TRUE and FALSE are function handles.
function RESULT = iff(CONDITION,TRUE,FALSE)
  if CONDITION
    RESULT = TRUE();
  else
    RESULT = FALSE();
  end
end

The function that creates the function handles of the accessor function:

1
2
3
4
5
function HANDLE = recordHandle(COLUMN, ROWS)
  HANDLE = @(row, column) (...
    iff(nargin == 2, @()COLUMN(ROWS(row), column), @()[size(COLUMN, 2), size(ROWS, 1)])...
  );
end