2
$\begingroup$

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

Result:

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?

$\endgroup$
4
$\begingroup$

Using the function matlabFunction increases the efficiency by a lot!

syms x
f = sin(x);
fp = diff(f,x);
F = matlabFunction(fp);
tic 
for i=1:1000
    F(0);
end
toc

tic 
for i=1:1000
    cos(0);
end
toc

Elapsed time is 0.037475 seconds.
Elapsed time is 0.004203 seconds.

Furthermore if the result of the symbolic calculations needs to be saved as a conventional function we can simply use matlabFunction(fp, 'file', 'myfunction') which will save the results to a function file.

$\endgroup$
  • $\begingroup$ This is a good approach, but it should be noted that the result of the function converted by matlabFunction will be calculated numerically, not symbolically (though from the question, the OP seems to be implicitly okay with this). $\endgroup$ – horchler Oct 28 '14 at 15:55
  • $\begingroup$ Do you want to evaluate to a symbolic expression rather than to a numerical expression? $\endgroup$ – nicoguaro Oct 28 '14 at 16:59
  • $\begingroup$ @nicoguaro The reason for using symbolic expressions was so that I could differentiate a messy expression knowing I would get the correct result. I would then want to evaluate it numerically. $\endgroup$ – Dipole Oct 28 '14 at 17:36
  • $\begingroup$ Understood, is symbolic toolbox of MATLAB good enough? $\endgroup$ – nicoguaro Oct 28 '14 at 17:44
  • $\begingroup$ @nicoguaro For my purposes it was, I think for differentiation it can go a long way, obviously it depends on your own requirements but I would say it is useful. $\endgroup$ – Dipole Oct 29 '14 at 15:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.