MATLAB: How to speed up evaluation of symbolic expression to numerical values for large number of evaluations

conversionevaluationexpressionfasterfunctionMATLABnumericalperformancespeedsymbolic

The usual way to evaluate (i-e get a numerical value) for specific values of input variables (more than one variable) is to either use "subs" function or create a symbolic function "symfun". It takes a long time if I try to repeat this process 50000 times in a "for" loop for different variable values.
For example, the following code took 10 minutes on a computer with pretty good processor and ram specifications.
>> syms x y z
f = 2*y*z*sin(x) + 3*x*sin(z)*cos(y) - z^3;
g(x,y,z) = gradient(f, [x, y, z])
tic
for i=1:50000
% d = double(subs(g,[x,y,z],[1,2,3]));
d = double(g(1,2,3));
end
toc
>> g(x, y, z) =
3*cos(y)*sin(z) + 2*y*z*cos(x)
2*z*sin(x) - 3*x*sin(y)*sin(z)
2*y*sin(x) - 3*z^2 + 3*x*cos(y)*cos(z)
>> Elapsed time is 600.937920 seconds.
 Is there a simple and faster way to achieve this workflow ?

Best Answer

The symbolic expression can be converted to a function handle or file using "matlabFunction" function.
The function handle generated by "matlabFunction" can also take vectors as input arguments. This way the evaluation of symbolic expression to numerical values can be vectorized.
Example Code:
% Get the desired symbolic expression
syms x y z
f = 2*y*z*sin(x) + 3*x*sin(z)*cos(y) - z^3;
g = gradient(f, [x, y, z]);
% convert symbolic expression to function handle
gFH = matlabFunction(g);
% Evaluate expression at corresponding values of variables
tic
x = 1:50000;
y = 2:50001;
z = 3:50002;
Out = gFH(x,y,z);
toc
>> Elapsed time is 0.005683 seconds.
Converting symbolic expression to a function and vectorization of workflow can help in reducing computation time significantly.
Please refer to following document for more information about "matlabFunction":