Use if clause in arrayfun in Octave/Matlab

China☆狼群 提交于 2020-01-02 04:05:15

问题


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?


回答1:


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.




回答2:


In MATLAB you don't need an if statement for the problem that you describe. In fact it is really simple to use arrayfun:

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

My guess is that it works in Octave as well.

Note that you don't actually need arrayfun in this case at all:

x>=2

Should do the trick here.



来源:https://stackoverflow.com/questions/16555724/use-if-clause-in-arrayfun-in-octave-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!