MATLAB: How to define a piecewise anonymous function

matlabfunctionpiecewisesyms

Hello everyone,
the example code
syms x
continuous_function = x^2+x;
matlabFunction(continuous_function,'Vars',x)
gives me the anonymous function
@(x)x+x.^2
I would like a similar result for piecewise functions. However, the code
syms x
piecewise_function = piecewise( 0<x<1, x, 'otherwiseVal', 0 );
matlabFunction(piecewise_function,'Vars',x)
does not work.
Thanks for any help!

Best Answer

You need to use ‘logical indexing’:
piecewise_function = @(x) (x.^2+x) .* ((0<x) & (x<1));
x = linspace(-1, 2);
figure
plot(x, piecewise_function(x))
producing:
How to define a piecewise anonymous function - 2019 05 31.png