Is there a Matlab conditional IF operator that can be placed INLINE like VBA's IIF

后端 未结 10 1334
滥情空心
滥情空心 2020-12-01 11:06

In VBA I can do the following:

A = B + IIF(C>0, C, 0)

so that if C>0 I get A=B+C and C<=0 I get A=B

10条回答
  •  一个人的身影
    2020-12-01 11:13

    Others have said already that there is no ternary ?: operator in Matlab. As a solution I suggest this function, which takes three functions instead of values. Therefore the amount of unnecessary calculations is minimized and you can check conditions before starting calculations, e.g. if a value is really numeric, or finite, or nonzero:

    function [ out ] = iif( condition, thenF, elseF, in, out)
    %iif Implements the ternary ?: operator
    %   out = iif (@condition, @thenF, @elseF, in[, out])
    %
    %   The result is equivalent to:
    %   condition(x) ? thenF(x) : elseF(x)
    %
    %   The optional argument out serves as a template, if the output type is
    %   different from the input type, e.g. for mapping arrays to cells and
    %   vice versa.
    %
    % This code is in the public domain.
    
    mask = condition(in);
    if nargin <= 4
      out = in;
    end
    
    if sum(mask)
      out(mask)  = thenF(in(mask));
    end
    if sum(~mask)
      out(~mask) = elseF(in(~mask));
    end
    
    end
    

    Use it like this:

    f = @(y)(iif(@(x)(x > 3), @(x)(x.^2), @(x)(x/2), y))
    f(linspace(0,6,10))
    

提交回复
热议问题