Loren on the Art of MATLAB

Turn ideas into MATLAB


Loren on the Art of MATLAB has been archived and will not be updated.

Delaying Evaluation of Function Inputs

When you call a function in MATLAB, MATLAB first evaluates all the inputs, and then passes these (possibly) computed values as the inputs. Recently Ljubomir Josifovski asked if there was a way to delay evaluation of function inputs and only evaluate them on demand. Here's what I came up with.


Use Anonymous Functions

Instead of calling the function with expressions as input values, create those expressions as anonymous functions with no inputs.


Let's create an array and an expression to evaluate.

a = rand(2000);
tic, f = @() a'*a, toc
f = 
Elapsed time is 0.003365 seconds.

You can see that setting up the anonymous function f doesn't take a lot of time.

Quick Comparison

We aren't passing arguments here, but comparing the direct computation time for a'*a with evaluating the same quantity via the anonymous function.

tic, b = a'*a; toc
tic, c = f(); toc
Elapsed time is 0.508455 seconds.
Elapsed time is 0.482722 seconds.

Setting up the function handle takes little time, but the evaluation is similar to the time for the expression itself.

This is what timeit, Steve Eddins' utility for benchmark timing, uses just this approach. timeit helps wash out first time evaluation costs and other timing artifacts that can show up in benchmarking. So let's try using that now for the anonymous function evaluation.

ans =

How To Take Advantage

Now, if you want your function to evaluate either expression 1 or expression 2 based on something criterion, you can do so by passing in the two expressions as anonymous functions and using some logic like this.

      if criterion == true
         y = expr1();
         y = expr2();

What's Your Strategy?

If you want to streamline your computations, do you have a strategy for delaying evaluation of expressions until necessary? How do you do this? Let me know here.

Published with MATLAB® 7.11

  • print


要发表评论,请点击 此处 登录到您的 MathWorks 帐户或创建一个新帐户。