I have a lengthy expression which is calculated using symbolic differentiation of a rather complicated function. I now intend to call this resulting (symbolic function) in a for loop many times, and so I would like to avoid having to perform the symbolic differentiation step every single iteration, rather I would like to "save" the result of the symbolic differentiation, so that on each loop I'm just evaluating a function. Maybe an example will help: Here we try to evaluate the cosine of zero using two ways.
syms x f = sin(x); fp = diff(f,x); fp = @(x) subs(fp, 'x', x); tic for i=1:1000 fp(0); end toc tic for i=1:1000 cos(0); end toc
Elapsed time is 3.654296 seconds. Elapsed time is 0.007301 seconds.
Hence using my symbolic function is super expensive! Is there anyway to mitigate this expensive function call?