Differenciation and Integration of piecewise functions

6 views (last 30 days)
Hello, I'm using matlab R2016a, and I cannot find a way to differentiate or integrate piecewise functions like the following:
f(x) = x if x<=1 and 2x if x>1
Can anyone help me? I need to do this both numerically and improperly Thanks Joao

Answers (1)

Walter Roberson
Walter Roberson on 7 Oct 2017
You mention you are using R2016a. For MATLAB R2008b to R2016a, the only way to do that symbolically is to dodge into MuPAD in order to create a piecewise expression inside the symbolic engine. This situation changed with R2016b, which added a piecewise() function call.
G = evalin(symengine, 'piecewise([x < 1, x], [x > 1, 2*x])');
You can then test with a few different values:
>> subs(G,x,[-1 0 1 2])
ans =
[ -1, 0, NaN, 4]
Notice the NaN: that is there because your expression does not define the result for x of exactly 1. Boundary conditions are important for integration!
You can then
>> int(G)
ans =
piecewise(1 < x, x^2, x < 1, x^2/2)
For numeric work, create a function:
function y = f(x)
y = nan(size(x));
mask = x < 1;
y(mask) = x(mask);
mask = x > 1;
y(mask) = 2 * x(mask);
You can then do
integral(@f,-5,5,'waypoints',1)
You need the 'waypoints' option because of the discontinuity.
You can cross-check with a numeric approximation:
x = linspace(-5,5,101);
y = f(x);
cumtrapz(x, y)
Why does this end in NaN? It's that pesky boundary condition again! If only some definite value had been assigned for the point at x = 1 ...

Community Treasure Hunt

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

Start Hunting!