Search code examples
matlabsymbolic-mathsymbolic-computation

How can I define f(x) = x/x in MATLAB (Symbolic Computation)


I try with these commands

x = sym('x');
f(x) = sym('f(x)');
f(x) = x/x;

and

f(x) = sym('x/x');

, but both of them produce

f(x) = 1

(yes.. for every real x including 0)

The question is how I can avoid the pre-evaluation in the command "sym", or there exists another way to handle this problem.

Thank you very much!

update 21.05.2014:

Let me describe the problem a little bit.

Consider

f(x) = x/x

and

g(x) = 1

It is obvious that domains of f and g are R-{0} and R respectively.

The automatic simplification in sym/syms may lead to lose some info.


Solution

  • The answer from @pabaldonedo is good. It seems that the designers of MuPad and the Symbolic Toolbox made a choice as x/x is indeterminate.

    If you actually want 0, Inf, -Inf, or NaN, to result in NaN rather than 1 then you can use symbolic variables in conjunction with an anonymous function:

    f = @(x)sym(x)./sym(x);
    f([-Inf -1 0 1 Inf NaN])
    

    which returns

    ans =
    
    [ NaN, 1, NaN, 1, NaN, NaN]
    

    Or, if the input is already symbolic you can just use this:

    f = @(x)x./x;
    f(sym([-Inf -1 0 1 Inf NaN]))