# How to create a conditional symbolic function?

40 views (last 30 days)
Oscar on 5 Dec 2014
Answered: Walter Roberson on 26 Aug 2018
Something like:
syms x
f(x) = sym('f(x)');
if (x>0 && x<=500)
f(x)=x^3;
elseif(x>500 && x<=1800)
f(x)=x^4;
else
fx(x)=x^2+100;
end

John Mahoney on 5 Dec 2014
Hi Oscar,
syms x
% Define each subfunction
f1 = x^3;
f2 = x^4;
f3 = x^2 + 100;
% Chop undesired ranges using heaviside / step function.
f1 = f1 * heaviside(x - 0) * (1 - heaviside(x - 500));
f2 = f2 * heaviside(x - 500) * (1 - heaviside(x - 1800));
f3 = f3 * (1 - heaviside(x - 0)) + f3 * heaviside(x - 1800);
f = f1 + f2 + f3;
% I plot the logarithm here since plotting f shows only the contribution from the dominant f2.
flog = log(f);
ezplot(flog, [-500, 3000])

Oscar on 5 Dec 2014
Excellent
moh pouladin on 26 Aug 2018
f(0)=50
But it have to equal 100.

Walter Roberson on 26 Aug 2018
The question was asked in 2014. Since that time, piecewise() was added in R2016b https://www.mathworks.com/help/symbolic/piecewise.html
Before that, you had to invoke MuPad's piecewise function using feval or evalin. I have posted the code in the past.
You have to be quite careful using Heaviside for this purpose, as Heaviside is not defined when the input expression is exactly 0. There are several different conventions for Heaviside(0), with it commonly being defined as 0, or 1, or 1/2, and sometimes even defined as infinity. MATLAB implemented sympref() to allow user control of Heaviside(0)
When you differentiate Heaviside you should get the Dirac delta distribution (which is not strictly a function.) But if you custom defined Heaviside(0) then you need to think carefully about whether dirac() is appropriate for the situation.
When you convert a piece wise description of a function to Heaviside calls, chances are that you need to toss in a dirac() for each boundary point to define the behavior right at the boundary correctly, especially for integration purposes.