A function can be defined as @(x) x^.2
(for e.g)
But in case, we have a function that takes different representation on different intervals for e.g : if abs(x)<3 fun = x^.2 else 0
How can we use the same way (i mean use @(x)
) to define such a function.
$var=function ($arg1, $arg2) { return $val; }; There is no function name between the function keyword and the opening parenthesis. There is a semicolon after the function definition because anonymous function definitions are expressions. Function is assigned to a variable, and called later using the variable's name.
An anonymous function is a function with no name which can be used once they're created. The anonymous function can be used in passing as a parameter to another function or in the immediate execution of a function.
Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement. For example, create a handle to an anonymous function that finds the square of a number: sqr = @(x) x.
The () makes the anonymous function an expression that returns a function object. An anonymous function is not accessible after its initial creation. Therefore, you often need to assign it to a variable. In this example, the anonymous function has no name between the function keyword and parentheses () .
There's a few ways to do this.
Multiply by false:
g = @(x) (abs(x)<3) .* x.^2
or define a proper function (the BEST way really):
function y = g(x)
y = zeros(size(x), class(x));
inds = abs(x)<3;
y(inds) = x(inds).^2;
end
or do the messy-ugly-inefficient-but-fun thing and use an inline-if:
iif = @(varargin) varargin{2 * find([varargin{1:2:end}], 1, 'first')}();
g = @(x) iff( ...
abs(x)<3, x.^2, ...
true, 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With