Search code examples
matlabsymbolic-mathmupad

Division by zero with symbolic functions


If I want to make a plot of y=1/x in Matlab I can use the following code:

X=-10:0.1:10;
Y=1./(X);
plot(X,Y);

But I would like to use symbolic functions so I can differentiate them, so I have this code:

syms x;
f(x) = 1./x;

X=-10:0.1:10;
Y=f(X);
plot(X,Y);

Unfortunately I get here an error

Error in MuPAD command: Division by zero. [_power]

This is reasonable as at some point it wil try to divide 1 by 0. How can I get this working so that it will return Inf when a division by zero occurs, just as in regular calculations of the form a=6/0;?


Solution

  • The ezplot function can be used to directly plot symbolic functions and expressions.

    syms x;
    f(x) = 1/x;
    ezplot(f,[-10 10]);
    

    If you want to convert your expression to something that can be evaluated numerically, you can use matlabFunction to convert the symbolic function to a function handle:

    syms x;
    f(x) = 1/x;
    X = -10:0.1:10;
    F = matlabFunction(f);
    plot(X,F(X));
    

    Why does't MuPAD return infinity for 1/0? In floating point, this is well-defined, but in mathematics, divison by zero is undefined. If you want to evaluate your function entirely in MuPAD you'll need to call underlying functions from Matlab and handle errors.