Symbolic differentiation using str2sym takes too long.

5 views (last 30 days)
My problem is to symbolically differentiate a series of functions (string expressions) as a loop operation. The previous method was using diff(sym(funstr), sym(varstr)) works about 2-times faster than the current one diff(str2sym(funstr),sym(varstr) - see examples below. Howecer, it sounds like the former can't be used in a future version. Unfoutunately, I have differentiate a few thousands functions one by one to build a Jacobian at the end, but I don't want to wait forever. Any solutions here?
tic
for k=1:1000
warning off
x=diff(sym('d/x+a*x+b+c+exp(x)+log(x)+y+z'),sym('x'));
warning on
end
toc
Elapsed time is 11.391776 seconds.
tic
for k=1:1000
x=diff(str2sym('d/x+a*x+b+c+exp(x)+log(x)+y+z'),str2sym('x'));
end
toc
Elapsed time is 27.391766 seconds.

Answers (1)

Steven Lord
Steven Lord on 6 Feb 2019
Don't redefine the variables each iteration through the loop. Define them as symbolic once and use them in the loop.
tic
syms a b c d x y z
for k = 1:1000
xd = diff(d/x+a*x+b+c+exp(x)+log(x)+y+z, x);
end
toc
  1 Comment
Tae Hoon Yang
Tae Hoon Yang on 11 Feb 2019
The operation suggested was also slow. The symbolic differentiation was much faster with MATLAB 2012b, but it looks like there is a problem. If you use jacobian instead of diff, it works somewhat faster. At the end, I had to build a cell-string array for the functions and variables, respectively, and use jacobian(str2sym(function cell array), str2sym(varialbe cell array)) to get the partial derivative expressions to be modified a posteriori. I am wondering what makes the symbolic differentiation so slow compared to the previous version like MATLAB 2012b version.

Sign in to comment.

Products


Release

R2017b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!