Vectorized function as output of matlabFunction

5 views (last 30 days)
I am trying to automatize a process in which I have a symbolic function that has to be converted in an anonymous function. Basically, I have something like this:
syms x y z t
var = [x y z t];
f = x.^2+y;
gf = gradient(f, var);
gf_fun = matlabFunction(gf, 'vars', {var});
having as output
gf_fun =
function_handle with value:
Now, I'd like to evaluate gf_fun in several var points at a time, but, of course, I got strange results, due to how gf_fun is written. For example, if I want to evaluate gf_fun in 6 (different) points simultaneously, what I get is
vv = ones(6,4);
ans =
instead of a matrix with dimensions 4x6, with each colomn being the evaluation of a single point.
I know that a workaround will be the use of a for loop, meaning that
results = zeros(4,6);
for i = 1:6
results(:,i) = gf_fun(vv(i,:));
but I have to avoid it due to code performances reasons.
Is there a way to automatize all the process, having a matrix as output of gf_fun while evaluating different point at a time?
Thank you for you help!

Accepted Answer

Srivardhan Gadila
Srivardhan Gadila on 18 Jul 2019
Hi CaG,
You can use the function “splitapply” . You can refer to the function at
I think you already noticed about the function "gf_fun", which
can provide different output based on the input dimension i.e., whether the input is row a vector or a column vector.
The following code provides the required output:
gff = @(x) gf_fun(x') %transpose the input
results = splitapply(gff,vv',1:6);

More Answers (0)


Find more on Symbolic Math Toolbox in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!