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.
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 = @()a'*a Elapsed time is 0.003365 seconds.
You can see that setting up the anonymous function f doesn't take a lot of time.
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 = 0.456538375738468
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(); else y = expr2(); end
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.
要发表评论，请点击 此处 登录到您的 MathWorks 帐户或创建一个新帐户。