在Octave/Matlab中的arrayfun中使用if子句 [英] Use if clause in arrayfun in Octave/Matlab

查看:141
本文介绍了在Octave/Matlab中的arrayfun中使用if子句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以像在Octave中一样在arrayfun中使用"if"?

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)

Octave抱怨:

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

arrayfun是否允许if子句?

Is if clause allowed in arrayfun?

推荐答案

在Octave中,不能以常规方式在嵌入式或匿名函数中使用if/else语句.您可以在自己的文件中定义函数,也可以将其定义为子函数,如下所示:

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

并像这样调用arrayfun:

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

更多信息 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆