MATLAB: How to create a conditional symbolic function

symbolic functionSymbolic Math Toolbox

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

Best Answer

Hi Oscar,
How about this?
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);
% Add em up
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])