Various functions depending on X

I wanted to create a function that consists of a number and functions and works like this
if x<-1 y=-x^2-4*x-2
if |x|<1 y=|x|
if x>1 y=2-e^(sqrt(x-1))

Réponses (1)

If the function is symbolic, then use piecewise.
help piecewise
--- 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. 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. Documentation for sym/piecewise doc sym/piecewise
Note that your function lacks definition, since you do not say what happens when x==1 or x==-1.
For a general matlab function, you can use my piecewise_eval, it is on the file exchange.
Pretty old now, but it should still work.
I also see many other tools on the FEX that claim to do the job too.

Catégories

En savoir plus sur Share and Distribute Software dans Centre d'aide et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by