# Saving symbolic function to increase efficiency in Matlab

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?

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.

• 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). – horchler Oct 28 '14 at 15:55
• Do you want to evaluate to a symbolic expression rather than to a numerical expression? – nicoguaro Oct 28 '14 at 16:59
• @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. – Dipole Oct 28 '14 at 17:36
• Understood, is symbolic toolbox of MATLAB good enough? – nicoguaro Oct 28 '14 at 17:44
• @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. – Dipole Oct 29 '14 at 15:31