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

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

    There is now a tern function on the MathWorks file exchange: http://www.mathworks.com/matlabcentral/fileexchange/39735-functional-programming-constructs/content/tern.m

    The code is reproduced here:

    function varargout = tern(condition, true_action, false_action)
    
    % out = tern(condition, true_action, false_action)
    % 
    % Ternary operator. If the first input is true, it returns the second
    % input. Otherwise, it returns the third input. This is useful for writing
    % compact functions and especially anonymous functions. Note that, like
    % many other languages, if the condition is true, not only is the false
    % condition not returned, it isn't even executed. Likewise, if the
    % condition is false, the true action is never executed. The second and
    % third arguments can therefore be function handles or values.
    %
    % Example:
    %
    % >> tern(rand < 0.5, @() fprintf('hi\n'), pi)
    % ans =
    %     3.1416
    % >> tern(rand < 0.5, @() fprintf('hi\n'), pi)
    % hi
    %
    % It works with multiple outputs as well.
    %
    % >> [min_or_max, index] = tern(rand < 0.5, ...
    %                               @() min([4 3 5]), ...
    %                               @() max([4 3 5]))
    % min_or_max =
    %      5
    % index =
    %      3
    %
    % Tucker McClure
    % Copyright 2013 The MathWorks, Inc.
    
        if condition() % Works for either a value or function handle.
            [varargout{1:nargout}] = true_action();
        else
            [varargout{1:nargout}] = false_action();
        end
    
    end
    

提交回复
热议问题