How to solve an equation with piecewise defined function?

조회 수: 5 (최근 30일)
Willow
Willow 2014년 10월 31일
댓글: Willow 2014년 11월 1일
Hi, I have been working on solving some equation in a more complicated context. However, I want to illustrate my question through the following simple example.
Consider the following two functions:
%%%%%%%%%%%%%%%%%%%%%
function y=f1(x)
y=1-x;
end
%%%%%%%%%%%%%%%%%%%%%
function y=f2(x)
if x<0
y=0;
else
y=x;
end
end
%%%%%%%%%%%%%%%%%%%%%
I want to solve the following equation: f1(x)=f2(x). The code I used is:
syms x;
x=solve(f1(x)-f2(x));
And I got the following error:
" ??? Error using ==> sym.sym>notimplemented at 2621
Function 'lt' is not implemented for MuPAD symbolic objects.
Error in ==> sym.sym>sym.lt at 812
notimplemented('lt');
Error in ==> f2 at 3
if x<0 "
I know the error is due to that x is a symbolic variable and therefore I could not compare x with 0 in the piecewise function f2(x).
But is there any way to fix this and solve the equation?
Thanks a lot!

답변 (1개)

Roger Stafford
Roger Stafford 2014년 10월 31일
Instead of using 'solve' you can use 'fzero' for this problem. Of course this problem is so simple you can do it in your head, namely, a single solution at x = 1/2. However in general 'fzero' can prove useful in solving problems where the function is defined piecewise, provided it is continuous. Those in your example are continuous. For functions with a jump discontinuity, 'fzero' could be "thrown for a loop" - that is, unable to find a solution.
  댓글 수: 1
Willow
Willow 2014년 11월 1일
I used fsolve instead of solve. Then the problem disappears even if the function is defined piece-wise.

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

카테고리

Help CenterFile Exchange에서 Numeric Solvers에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by