Section 8.7 Anonymous Functions with Multiple Arguments
As we saw before, anonymous functions can have multiple independent variables.
Here is an example: Suppose that A and B are points in the plane whose distance we wish to find. The points are given to us in polar coordinates \((r_a,\theta_a)\) and \((r_b,\theta_b)\) as you can see in this picture:
Using the law of cosines you can find the following formula for the distance d:
\begin{equation*}
d = \sqrt{r_a^2 + r_b^2 - 2r_ar_b\,cos(\theta_b-\theta_a)}
\end{equation*}
Here is how you would define this function in MATLAB:
>> pdist = @(ra,ta,rb,tb) sqrt(ra.^2 + rb.^2 – 2*ra.*rb.*cos(tb-ta));
>> dAtoB = pdist(2,pi/6, 5,3*pi/4)
dAtoB =
5.8461
A word of caution. The expression that defines the anonymous function can include pre-assigned MATLAB variables.
a = 2;
b = 3;
ellipse = @ (x, y) a*x^2 + b*y^2
IMPORTANT:
The values are captured when the function is defined, i.e. the function is NOT changed when new values are assigned to
a
and b
.