Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matlab inline function with special handling for zero

I have a function that has a singularity at zero. The resulting value should be at that point 1.

However I fails to understand how to create an inline function that has a special treatment for values of x and y at x or y = 0.

The function could for example be

f = @(x,y) ( 1./x + 1./y ); 
like image 811
Matthias Pospiech Avatar asked Jul 18 '26 15:07

Matthias Pospiech


2 Answers

To answer your question with a counter-question: why do you want it to be inline?

As a general rule, keep inline functions simple. If more functionality is needed, use a dedicated function:

function val = f(x,y)

    if ~all(size(x)==size(y))
        error('sizes must match');

    val = zeros(size(x));

    zero_x = x==0;
    zero_y = y==0;

    not_zero = ~zero_x & ~zero_y;
    zero = ~not_zero;

    val(not_zero) = 1./x(not_zero) + 1./y(not_zero);
    val(zero) = 1;           

end

Having said that, there are of course ways to do it inline (see other answers).

But as you indicated, your actual function is more complex, so...why inline?

like image 186
Rody Oldenhuis Avatar answered Jul 20 '26 08:07

Rody Oldenhuis


Create the following iif.m function file, residing in your working folder, or even as a subfunction if you're using it in other functions (scripts of course can not contain subfunctions):

function val = iif(expr, truepart, falsepart)
    if isscalar(truepart)
        truepart=truepart(ones(size(expr)));
    end
    if isscalar(falsepart)
       falsepart=falsepart(ones(size(expr))); 
    end
    val = arrayfun(@iif_scalar, expr, truepart, falsepart);
end
function val = iif_scalar(expr,truepart,falsepart)
    if expr
        val = truepart;
    else
        val = falsepart;
    end
end

and use it as follows:

f = @(x,y) iif(x==0 | y==0, 1, 1./x + 1./y );

I kept the iif function as general as possible, you can use it on vectors, scalars, mixed scalar and vectors, or even matrices. For example, in the above I used 2 vectors and a scalar:

iif( ...
     x==0 | y==0 ,... % expression if x or y are 0 => vector
     1 , ...          % scalar obviously
     1./x + 1./y ...  % function of x and y => vector
   )
like image 45
Gunther Struyf Avatar answered Jul 20 '26 09:07

Gunther Struyf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!