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

后端 未结 10 1327
滥情空心
滥情空心 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:16

    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.

提交回复
热议问题