필터 지우기
필터 지우기

How to define a piecewise anonymous function

조회 수: 42 (최근 30일)
Stephan
Stephan 2019년 5월 31일
댓글: Star Strider 2020년 5월 16일
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!

채택된 답변

Star Strider
Star Strider 2019년 5월 31일
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
  댓글 수: 6
ElPerroVerde
ElPerroVerde 2020년 5월 16일
THANK YOU SO MUCH!!!!!!!!!!!! I've been looking for something like this for months!!!
Star Strider
Star Strider 2020년 5월 16일
ElPerroVerde — My pleasure!
A Vote would be appreciated!
.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Walter Roberson
Walter Roberson 2020년 5월 16일
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.

카테고리

Help CenterFile Exchange에서 Conversion Between Symbolic and Numeric에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by