checkGradients, but the objective function has two inputs: x and xdata?

48 visualizaciones (últimos 30 días)
Benjamin Pepper
Benjamin Pepper el 14 de Nov. de 2024 a las 10:21
Comentada: Torsten el 21 de Nov. de 2024 a las 21:34
I'm using lsqcurvefit with the following objective function and Jacobian:
function [f, jacF] = semiCircle(p, Q)
P0 = p(1);
Q0 = p(2);
r = p(3);
f = P0 + sqrt(r^2 - (Q-Q0).^2);
if nargout > 1 % need Jacobian
jacF = [1, (Q-Q0)./sqrt(r^2-(Q0-Q).^2), r./sqrt(r^2-(Q0-Q).^2)];
end
end
I'd like to use checkGradients to verify if the Jacobian is correct. However, all of the examples in the documentation just have objective functions with one input, the parameters 'x'. Whereas my function semiCircle has two inputs: the parameters 'p' and the xdata 'Q'. Is there a way to use checkGradients for such a function?

Respuesta aceptada

Torsten
Torsten el 14 de Nov. de 2024 a las 10:31
valid = checkGradients(@(p)semiCircle(p, Q),p0)
  10 comentarios
Benjamin Pepper
Benjamin Pepper el 21 de Nov. de 2024 a las 11:39
Editada: Torsten el 21 de Nov. de 2024 a las 21:30
I reached my daily uploads limit, so I'll just put the functions here:
load('data.mat')
Vb_ll_rms = 690;
% Inital guess
p10 = 5e6;
p20 = 2.5e7;
p30 = 3e7;
p0 = [p10, p20, p30];
[Rls, Xls, Vgls, gradientCheck] = lsqcurvefitNLS(p0, Q, P, Vb_ll_rms)
Rls = 0.0024
Xls = 0.0238
Vgls = 689.9365
gradientCheck = logical
1
function [R, X, Vg, gradientCheck] = lsqcurvefitNLS(p0, Q, P, Vo)
% Box constraints
p1_ub = min(P);
p2_lb = max(Q);
p3_lb = max(Q) - min(Q);
lb = [0, p2_lb, p3_lb];
ub = [p1_ub, inf, inf];
% Linear constraints
A = [0, 1, -1];
b = min(Q);
gradientCheck = checkGradients(@(p)semiCircle(p,Q),p0);
options = optimoptions('lsqcurvefit','Display','off','SpecifyObjectiveGradient',true);
p = lsqcurvefit(@semiCircle, p0, Q, P, lb, ub, A, b, [], [], [], options);
P0 = p(1);
Q0 = p(2);
r = p(3);
R = P0/(P0^2 + Q0^2)*Vo^2;
X = Q0/(P0^2 + Q0^2)*Vo^2;
Vg = sqrt(r^2/(P0^2 + Q0^2)*Vo^2);
end
And the other one:
function [f, jacF] = semiCircle(p, Q)
P0 = p(1);
Q0 = p(2);
r = p(3);
f = P0 + sqrt(r^2 - (Q-Q0).^2);
if nargout > 1 % need Jacobian
jacF = zeros(length(Q), length(p));
for i = 1:length(Q)
jacF(i,:) = [1, (Q(i)-Q0)/sqrt(r^2-(Q0-Q(i))^2), r/sqrt(r^2-(Q0-Q(i))^2)];
end
end
end
Torsten
Torsten el 21 de Nov. de 2024 a las 21:34
As you said: the code works fine with R2024b.
But note that the call to "lsqcurvefit" has changed in R2023a to the actual call that you use in the code. So if your desktop MATLAB version is older than R2023a, linear constraints (A,b) are not yet accepted.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre Programming en Help Center y File Exchange.

Productos


Versión

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by