Search code examples
matlabexportpolynomial-mathmupad

Extracting polynomial from MuPAD to Matlab


I have poly in MuPAD (one variable, several parameters). I want to extract it somehow to Matlab.

An example of poly in MuPAD:

poly((-7/(2*k^2))*X^2 + ((7*(b + k))/(2*k^2) + (7*(b + 2*k))/(2*k^2) + 4/k)*X + (- (b + k)*((7*(b + 2*k))/(2*k^2) + 4/k) + 1), [X])

I want to get it in Matlab:

x*((7*(b + k))/(2*k^2) + (7*(b + 2*k))/(2*k^2) + 4/k) - (7*x^2)/(2*k^2) - (b + k)*((7*(b + 2*k))/(2*k^2) + 4/k) + 1

Is there any handy way to do this? P.S. Matlab R2015a


Solution

  • I believe that you want to convert the MuPAD object of domain DOM_POLY to a general symbolic expression. You can use the expr function for this. I'm assuming that you're already working from within Matlab here (from within MuPAD, it's just expr(p1)):

    syms b k X
    p1 = feval(symengine,'poly',(-7/(2*k^2))*X^2 + ((7*(b + k))/(2*k^2) + (7*(b + 2*k))/(2*k^2) + 4/k)*X + (- (b + k)*((7*(b + 2*k))/(2*k^2) + 4/k) + 1),'[X]')
    p2 = feval(symengine,'expr',p1)
    

    which returns

    p2 =
    
    X*((7*b + 7*k)/(2*k^2) + (7*b + 14*k)/(2*k^2) + 4/k) - (b + k)*((7*b + 14*k)/(2*k^2) + 4/k) - (7*X^2)/(2*k^2) + 1
    

    You can also use matlabFunction to convert either form (p1 or p2 above) to a vectorized floating point function handle, e.g.:

    f = matlabFunction(p1,'Vars',{b k X})
    

    which returns

    f = 
    
        @(b,k,X)-(b+k).*(1.0./k.^2.*(b.*7.0+k.*1.4e1).*(1.0./2.0)+4.0./k)+X.*(1.0./k.^2.*(b.*7.0+k.*7.0).*(1.0./2.0)+1.0./k.^2.*(b.*7.0+k.*1.4e1).*(1.0./2.0)+4.0./k)-X.^2.*1.0./k.^2.*(7.0./2.0)+1.0