=2 1 els...">

Use if argument in arrayfun in Octave / Matlab

Is it possible to use "if" in arrayfun, as 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 the sentence allowed in arrayfun?

+4
source share
2 answers

In Octave, you cannot use the if / else statements of an inline or anonymous function in the usual way. You can define your function in your 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 as follows:

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

Or you can use this work with a built-in function:

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

More information here .

+6
source

In MATLAB, you do not need an if statement for the problem described. It is actually very simple to use arrayfun:

 arrayfun(@(x) x>=2, a) 

I guess it works on Octave too.

Note that in this case you do not need arrayfun at all:

 x>=2 

Here you need to do the trick.

+4
source

Source: https://habr.com/ru/post/1480831/


All Articles