How to set a function that can return different value for different range in MatLab? - piecewise -- MatLab

 How to set a function that can return different value for different range in MatLab? - piecewise -- MatLab






[Ans]

piecewise command

[Description]

I think explanations of matlab help doc are
I think I can not use greater way to describe

--- help for sym/piecewise ---

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.

[Syntax]


Type of <otherval> must be constant.

If <otherVal> was not given, it is NaN by default.
more details on:

[Code]



I think the example from matlab help doc is great, so I uses these examples.
clear
clc
syms x
pw = piecewise(x<0, -1, x>=0 & x<2, 2)
subs(pw, x, -2) %-1
subs(pw, x, 1) %2
subs(pw, x, 3) %NaN
% this cause compiler error.
%pw(7)
syms x
pw = piecewise(x<0, 0, x)
subs(pw, x, -2) %0
%same as subs(pw,x,real(1i))
subs(pw, x, 1i) %1i
%pw(x) is a function
syms pw(x) y
pw(x) = piecewise(x>0, 1, x < 0, -1, 0)
pw(-5)%-1
pw(0)%0
assume(y>2)
pw(y)%1




Comments