Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use conditions within an anonymous function

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.

like image 805
Jessica Avatar asked Jul 02 '13 08:07

Jessica


People also ask

How do you use variables in anonymous functions?

$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.

Can anonymous functions have parameters?

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.

Can anonymous functions have multiple inputs?

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.

What is the syntax for an anonymous function?

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 () .


1 Answers

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);
like image 138
Rody Oldenhuis Avatar answered Sep 20 '22 01:09

Rody Oldenhuis