简体   繁体   中英

How to solve an equation with piecewise defined function in Matlab?

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 because x is a symbolic variable and therefore I could not compare x with 0 in the piecewise function f2(x) .

Is there a way to fix this and solve the equation?

First, make sure symbolic math is even the appropriate solution method for your problem. In many cases it isn't. Look at fzero and fsolve amongst many others. A symbolic method is only needed if, for example, you want a formula or if you need to ensure precision.

In such an old version of Matlab, you may want to break up your piecewise function into separate continuous functions and solve them separately:

syms x;
s1 = solve(1-x^2,x) % For x >= 0
s2 = solve(1-x,x)   % For x < 0

Then you can either manually examine or numerically compare the outputs to determine if any or all of the solutions are valid for the chosen regime – something like this:

s = [s1(double(s1) >= 0);s2(double(s2) < 0)]

You can also take advantage of the heaviside function, which is available in much older versions.

syms x;
f1 = 1-x;
f2 = x*heaviside(x);
s = solve(f1-f2,x)

Yes, the Heaviside function is 0.5 at zero – this gives it the appropriate mathematical properties. You can shift it to compare values other than zero. This is a standard technique.

In Matlab R2012a+, you can take advantage of assumptions in addition to the normal relational operators. To add to @AlexB's comment, you should convert the output of any logical comparison to symbolic before using isAlways :

isAlways(sym(x<0))

In your case, x is obviously not "always" on one side or the other of zero, but you may still find this useful in other cases.

If you want to get deep into Matlab's symbolic math, you can create piecewise functions using MuPAD , which are accessible from Matlab – eg, see my example here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM