Search code examples
matlabmatrixoctavescientific-computing

Use if clause in arrayfun in Octave/Matlab


Is it possible to use "if" in arrayfun like the following in Octave?

a = [ 1 2; 3 4];
arrayfun(@(x) if x>=2 1 else 0 end,  a)

And Octave complains:

>>> arrayfun(@(x) if x>=2 1 else 0 end, a)
                                     ^

Is if clause allowed in arrayfun?


Solution

  • In Octave you can't use if/else statements in an inline or anonymous function in the normal way. You can define your function in it's own file or as a subfunction like this:

    function a = testIf(x)
         if x>=2
            a = 1;
         else 
            a = 0;
         end
     end
    

    and call arrayfun like this:

    arrayfun(@testIf,a)
    ans =
    
       0   1
       1   1
    

    Or you can use this work around with an inline function:

    iif = @(varargin) varargin{2 * find([varargin{1:2:end}], 1, ...
                                         'first')}();
    
    arrayfun(iif, a >= 2, 1, true, 0)
    ans =
    
       0   1
       1   1
    

    There's more information here.