Search code examples
matlabcoefficientstaylor-series

Simplify symbolic expression in matlab and get only the coeeficents


I'm looking for finding the coefficients from the Taylor's series in Matlab. The way that I'm doing is:

% Declare symbolic expression and function:
syms x;
f = exp(x);

% Calculate the taylor expansions in a concrete point:
T = taylor(f, x, 0.5);

% And finally I simplify the expression:
coefs = simplify(T)

But the returned expression is:

Yes, the expression it's simplified, but actually what I want is:

Where each term is multiplied by his coefficient. How can I this? Options suchs as simplify(f, x, 0.5, 10, where 10 refers to the simplification step,doesn't work in my case. Also I've been seeing this question and the problem is the same:

How get to simplify a symbolic and numeric mixed expression in Matlab


Solution

  • Depending on how many digits you want and in what exact format you want the result, here is an example:

    >> c = double(coeffs(T))
    c =
      Columns 1 through 4
       0.999966624859531   1.000395979357109   0.498051217190664   0.171741799031263
      Columns 5 through 6
       0.034348359806253   0.013739343922501
    >> digits 15
    >> x.^(0:numel(c)-1) * sym(c,'d').'
    ans =
    0.0137393439225011*x^5 + 0.0343483598062527*x^4 + 0.171741799031263*x^3 + 0.498051217190664*x^2 + 1.00039597935711*x + 0.999966624859531
    

    EDIT

    Note that you could also use vpa( ) instead of converting to double first:

    >> c = coeffs(T)
    c =
    [ (2329*exp(1/2))/3840, (233*exp(1/2))/384, (29*exp(1/2))/96, (5*exp(1/2))/48, exp(1/2)/48, exp(1/2)/120]
    >> x.^(0:numel(c)-1) * vpa(c).'
    ans =
    0.0137393439225011*x^5 + 0.0343483598062527*x^4 + 0.171741799031263*x^3 + 0.498051217190664*x^2 + 1.00039597935711*x + 0.999966624859531