![How to define a piecewise anonymous function - 2019 05 31.png](https://www.mathworks.com/matlabcentral/answers/uploaded_files/222232/How%20to%20define%20a%20piecewise%20anonymous%20function%20-%202019%2005%2031.png)
How to define a piecewise anonymous function
38 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Stephan
el 31 de Mayo de 2019
Comentada: Star Strider
el 16 de Mayo de 2020
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!
0 comentarios
Respuesta aceptada
Star Strider
el 31 de Mayo de 2019
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](https://www.mathworks.com/matlabcentral/answers/uploaded_files/222232/How%20to%20define%20a%20piecewise%20anonymous%20function%20-%202019%2005%2031.png)
6 comentarios
ElPerroVerde
el 16 de Mayo de 2020
THANK YOU SO MUCH!!!!!!!!!!!! I've been looking for something like this for months!!!
Más respuestas (1)
Walter Roberson
el 16 de Mayo de 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.
0 comentarios
Ver también
Categorías
Más información sobre Assumptions en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!