gusucode.com > symbolic工具箱matlab源码程序 > symbolic/@sym/piecewise.m

    function pw = piecewise(varargin)
%PIECEWISE Conditionally defined symbolic object
%   PW = PIECEWISE(CONDITION1, VAL1, CONDITION2, VAL2, ..., <OTHERWISEVAL>)
%
%   Create a conditionally defined symbolic object. It equals the k-th
%   value if the k-th condition holds and the first k-1 conditions are
%   false. If all conditions are false, it equals otherwiseVal.
%   The final argument otherwiseVal may be omitted; it defaults to sym(NaN).
%   In contrast to an if statement, the truth value of the conditions need
%   not be decidable at the time the conditional object is defined.
%
%   Example:
%      syms x
%      pw = piecewise(x<0, -1, x>=0 & x<2, 2)
%      subs(pw, x, -2)
%      subs(pw, x, 1)
%      subs(pw, x, 3)
%
%      syms x
%      pw = piecewise(x<0, 0, x)
%      subs(pw, x, -2)
%      subs(pw, x, 1i)
%
%      syms pw(x) y
%      pw(x) = piecewise(x>0, 1, x < 0, -1, 0)
%      pw(-5)
%      pw(0)
%      assume(y>2)
%      pw(y)
%
%   See also IF, SYM/ASSUME, SYM/ASSUMEALSO.

%   Copyright 2016 MathWorks, Inc.

args = privResolveArgs(varargin{:});
% if the number of arguments is odd, add true before the last argument
if mod(size(args, 2), 2) == 1
  args(end: end+1) = {evalin(symengine, 'TRUE'), args{end}};
end
% reshape such that each column contains a branch
branches = reshape(args, 2, []);
% convert to MuPAD lists
n = size(branches, 2);
lists = cell(n, 1);
for k = 1: n
  lists{k} = feval(symengine, 'DOM_LIST', branches{:, k});
end

pw = feval(symengine, 'piecewise', lists{:}, 'ExclusiveConditions');
pw = privResolveOutput(pw, args{1});