Symbolic differentiation using str2sym takes too long.
5 views (last 30 days)
Show older comments
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.
0 Comments
Answers (1)
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
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!