### 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:

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.

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