Is there a Matlab conditional IF operator that can

2019-01-09 00:47发布

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

Is there an operator or function that will let me do these conditionals inline in MATLAB code?

7条回答
Bombasti
2楼-- · 2019-01-09 01:35

Inspired by Jonas' answer the function below also works for mixed type input and chars, for which his function isn't stable.

function out = iif(cond, a, b)
%IIF implements a ternary operator

    % Use cell output for either char or mixed type input
    if ischar(a) || ischar(b) || ~strcmp(class(a), class(b))
        out = cell(size(cond));
        [out{cond}] = deal(a);
        [out{~cond}] = deal(b);
    else
        % Use array output and logical indexing
        out = repmat(b, size(cond));
        out(cond) = a;
    end
end

Edit: weeded out the extra conditional options in the cell branch, which were apparently remnants of a previous mistake, this is probably faster, and definitely cleaner.

查看更多
登录 后发表回答