How to solve an equation with piecewise defined function?
18 views (last 30 days)
Show older comments
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!
0 Comments
Answers (1)
Roger Stafford
on 31 Oct 2014
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.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!