I'm having some problems when using the symsum
function in MATLAB's Symbolic Math Toolbox. My code should be returning:
ans = sin(x) + x*cos(x) - x^2 / 2 * sin(x)
I think it has something to do with symbolic variables, but I'm new into MATLAB so help will 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 indicated above.
This occurs because diff(f,x,i)
evaluates to zero. When using symsum
, you need to be aware that, like with any Matlab function, the input arguments will be evaluated before being passed in. Just use a for
loop (sym/diff
is 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 could try this form (in this case, for just three indexes, the 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 does diff(f,x,i)
evaluate to zero even though i
is symbolic? 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 doesn't support symbolic variables to specify the order of integration. The order, n
(or i
in your code) is also limited to a scalar. MuPAD's related functions have similar limitations as well unfortunately.
In my opinion, sym/diff
should throw an error if it has this limitation rather than returning garbage. I'd recommend that you file a service request with The MathWorks to report this issue. You could also request that the function be updated to handle symbolic variables for the order of integration input.