How to use conditions within an anonymous function
10,926
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);
Author by
Jessica
Updated on June 04, 2022Comments
-
Jessica almost 2 years
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.