Help with converting symbolic gradient/Hessian to anonymous function

3 Ansichten (letzte 30 Tage)
Hi,
I have a symbolic function f, which is a function of a 2x1 symbolic vector. I've taken the gradient and Hessian of it without issue. However, I want to convert both of them to anonymous functions, so that I can input some vector double x0 (like [1; 1] for example), and return a 2x1 vector double for the gradient and a 2x2 matrix double for the Hessian. I've been using matlabFunction, but it always splits the symbolic inputs into two inputs x1 and x2, whereas I want one input, the vector x. I've tried specifying the variables that matlabFunction is to use by getting MATLAB to detect the symbolic variables in the function f with symvar, and tried to just input the original symbolic vector x, but neither works. Interestingly, the Hessian anonymous function has no issue with a single input, but maybe that's because in my case the Hessian in constant anyways. Anyways, here's my code:
% define function
syms x [2, 1]
f = x(1)^2 + x(2)^2 - 6*x(1) - 2*x(2) + 10;
% define initial guess
x0 = [1; 1];
xMinNM = newmet(f, x, x0);
function x = newmet(f, x, x0)
fSyms = symvar(f);
% find gradient and hessian
grad = gradient(f, x);
H = hessian(f, x);
if isa(grad, 'sym')
grad = matlabFunction(grad, 'Vars', x); % alternatively, replace x with fSyms
end
if isa(H, 'sym')
H = matlabFunction(H, 'Vars', x); % alternatively, replace x with fSyms
end
% other stuff i didn't copy
% |
% |
% |
% v
end
Thanks!

Akzeptierte Antwort

Walter Roberson
Walter Roberson am 11 Mär. 2025
matlabFunction(grad, 'Vars', {x})
When you pass a cell array as Vars, then each element of the cell array is a group of variables to be bundled together into the same input parameter.
  4 Kommentare
Cole
Cole am 11 Mär. 2025
I appreciate the in-depth answer, it makes a lot more sense now.
Thanks!
Matt J
Matt J am 11 Mär. 2025
@Cole You should Accept-click the answer, since it appears to have resolved your question.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Tags

Produkte


Version

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by