Vectorized function as output of matlabFunction

2 ビュー (過去 30 日間)
CaG
CaG 2019 年 7 月 9 日
回答済み: Srivardhan Gadila 2019 年 7 月 18 日
Hi.
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:
@(in1)[in1(:,1).*2.0;1.0;0.0;0.0]
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
rng('deafult')
vv = ones(6,4);
gf_fun(vv)
ans =
1.3575
1.5155
1.4863
0.7845
1.3110
0.3424
1.0000
0
0
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,:));
end
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!

採用された回答

Srivardhan Gadila
Srivardhan Gadila 2019 年 7 月 18 日
Hi CaG,
You can use the function “splitapply” . You can refer to the function at https://www.mathworks.com/help/matlab/ref/splitapply.html.
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);

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeSymbolic Math Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by