Problems with symsum () function in Symbolic Math Toolbox

I am having some problems when using a function symsum

in MATLAB Symbolic Math Toolbox. My code should return:

ans = sin(x) + x*cos(x) - x^2 / 2 * sin(x)

      

I think it has something to do with symbolic variables, but I am new to MATLAB, so help would be appreciated.

Here's my code:

syms x i;
f(x) = sin(x);

symsum(x^i/factorial(i)*diff(f,x,i), i, 0, 2)

      

which returns 0

instead of the correct result above.

+3


source to share


1 answer


This is because it diff(f,x,i)

evaluates to zero. When using, symsum

you need to know that, like any Matlab function, the input arguments will be evaluated before being passed. use a loop for

( sym/diff

not vectorized in the third argument - see below):

syms x y;
f(x) = sin(x);
n = 0:2;
y = 0;
for i = n
    y = y+x^i/factorial(i)*diff(f,x,i);
end

      

Alternatively, you can try this form (in this case, just three indices above will probably be more efficient):

syms x y;
f(x) = sin(x);
n = 0:2; % Increasing orders of differentiation
y = diff(f,x,n(1));
yi = [y(x) zeros(1,length(n)-1)]; % To index into array, yi cannot be symfun
for i = 2:length(n)
    % Calculate next derivative from previous
    yi(i) = diff(yi(i-1),x,n(i)-n(i-1));
end
% Convert yi back to symfun so output is symfun
y = sum(x.^n./factorial(n).*symfun(yi,x));

      




Why diff(f,x,i)

is it evaluated to zero even though it i

is a symbol? From the documentation for sym/diff

:

diff (S, n), for a positive integer n, differentiates S n times.   diff (S, 'v', n) and diff (S, n, 'v') are also acceptable.

In other words, the function does not support symbolic variables to indicate the order of integration. The order, n

(or i

in your code) is also limited by a scalar. Unfortunately, MuPAD related features also have similar limitations.

In my opinion, sym/diff

should throw an error if it has this constraint, not a garbage return. I would recommend that you submit a service request to MathWorks to report this issue. You can also request a function update to handle symbolic variables for the integration input order.

+2


source







All Articles