493: Undecipherable

-About me-

-Projects-

-Publications-

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   a=2 
2   b=2 
3   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 %%Artificial if for use in anonymous functions
2 %TRUE and FALSE are function handles.
3 function RESULT = iff(CONDITION,TRUE,FALSE)
4   if CONDITION
5     RESULT = TRUE();
6   else
7     RESULT = FALSE();
8   end
9 end

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

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