Lazy evaluation is primarily used in functional programming languages and MATLAB is procedural/OOP based. As such, an equivalent of SetDelayed
does not exist. If you try to use anonymous functions as you've demonstrated, it will not work, as Amro has already pointed out.
However, if you have access to the symbolic computing toolbox, you can get by with something that could be considered an equivalent of :=
(a flimsy equivalence, if you ask me). Here's an example:
syms x y z; %#Declare x, y and z as symbolic variables
x=y+2; %#Define some value for x
f=@(x)x.^2; %#Define an anonymous function.
f(x)
ans =
(y + 2)^2
%#Check with z
f(z)
ans =
z^2
You can see that it uses the actual definition of f
, and does not capture the definition of x
as it did in your numerical example. You can also change the definition of x
to say, x=1/y
and f(x)
will now use the present definition of x
. Note that f
is merely a function handle and will take numerical/symbolic arguments. E.g.,
f(1:5)
ans =
1 4 9 16 25
The part where it does not resemble :=
is that it applies the definitions only for the terms present in the expression and does not go deeper (i.e., it does not evaluate the definitions for the different set of variables that might arise as a result of the first evaluation). This is hardly a surprise as MATLAB is not a rule based language. To illustrate my point:
y=z^3; %#Define y
f(x)
ans =
(y + 2)^2 %#The definition for y is not used.
whereas Mathematica would've given you (z^3+2)^2
.
Clear[y, z, x, f]
f[x_] := x^2;
y := z^3; x := y + 2;
f[x]
Out[1]= (2 + z^3)^2
It is best if you embraced the differences in the two languages and tried to stick with what is idiomatic in each. Trying to deny it and program in one like the other could make your life miserable (e.g., starting with a C background and adamantly writing For
loops in Mathematica).