How to define a piecewise anonymous function

182 views (last 30 days)
Stephan on 31 May 2019
Commented: Star Strider on 16 May 2020
Hello everyone,
the example code
syms x
continuous_function = x^2+x;
gives me the anonymous function
I would like a similar result for piecewise functions. However, the code
syms x
piecewise_function = piecewise( 0<x<1, x, 'otherwiseVal', 0 );
does not work.
Thanks for any help!

Accepted Answer

Star Strider
Star Strider on 31 May 2019
You need to use ‘logical indexing’:
piecewise_function = @(x) (x.^2+x) .* ((0<x) & (x<1));
x = linspace(-1, 2);
plot(x, piecewise_function(x))
How to define a piecewise anonymous function - 2019 05 31.png
Star Strider
Star Strider on 16 May 2020
ElPerroVerde — My pleasure!
A Vote would be appreciated!

Sign in to comment.

More Answers (1)

Walter Roberson
Walter Roberson on 16 May 2020
If you use matlabFunction with 'file' option, then it will convert piecewise() into if/else in the generated code.
Note: because it uses if/else instead of logical indexing, the generated code will not be vectorized on that variable.

Community Treasure Hunt

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

Start Hunting!