Search code examples
matlabsymbolic-math

Plotting a piecewise symbolic expression in MATLAB using ezplot


I have created the following symbolic integral:

syms x; 
syms t; 
int(1./((1-t.*x).^3),t,0,1)

ans =
    piecewise([x = 1, Inf], [not 1/x in (0, 1) and x 1, -(x/2 - 1)/(x - 1)^2])

which results in a piecewise function definition. Now I want to plot this integral using the ezplot function, but this leads to an error:

Error using ezplot (line 162)
piecewise([1/x in Dom::Interval([0], [1]), -int(1/(t*x - 1)^3, t, 0, 1)], 
   [~1/x in Dom::Interval([0], [1]), -(x - 2)/(2*(x - 1)^2)]) 
   cannot be plotted in the xy-plane.

Error in sym/ezplot (line 61)
   h = ezplot(fhandle(f));

How can I plot this piecewise symbolic integral?


Solution

  • Though I could not find any evidence by Mathworks, it seems that ezplot does not work together with piecewise symbolic functions (Source: there are a few open questions on exactly this topic in the Matlab help forum).

    In this answer I am presenting a work-around, which works for explicit, invertible functions, i.e. it will fail for stuff like x^2 + y^2 = 1 or y^2 = y^4 , and similar stuff. In this special case (which I assume is used most often), one can manually generate a x-vector and calculate the corresponding y-values using the subs function.

    The default range for ezplot is [-2pi, 2pi]. The number of points depends strongly on the function, but with around 1000 points, a reasonably smooth plot should be created. Note: This should produce the default ezplot behavior. If you have further knowledge about the function, i.e. value ranges etc., you should definitely use this to create the x vector.

    xp = -2*pi : 0.01: 2*pi;
    yp = subs(f, x, xp);
    plot(xp,yp);