I'm trying to write a function that accepts a function vector of any size and return the numerical Jacobian matrix.

2 vues (au cours des 30 derniers jours)
The answer should be x=1.2812, y=2.5349 and z=-0.5022 but once I put the loop, I'm getting these values x=0.9794, y=2.9794 and z=-0.0206
This is my function script:
function J = jacobian_numeric(f,x,h)
[m,n] = size(x);
for ii = 1:n
hv = zeros(1,n);
hv(1,ii) = h;
J(:,ii) = (f(x+hv) - f(x-hv))./(2*h);
end
end
And this is the m-file that calls the function:
clear; clc;
f = @(x) [(x(1).^2 - x(2) - x(1).*x(3) + 0.25) ; (x(1).*x(2) + x(3).^2 - 3.5) ; (sin(pi.*x(1)) - x(2).*x(3) - 0.5)];
x0 = [1 ; 3 ; 0];
h = 0.00001;
tol = 1e-5;
err = 1 + tol;
iter = 0;
while err > tol
J = jacobian_numeric(f,x0,h);
xold = x0;
x0 = x0 - J \ f(x0);
iter = iter + 1;
err = max(abs((x0 - xold)./(x0)));
end
x = x0(1,1)
y = x0(2,1)
z = x0(3,1)
I tried many things but nothing worked, so I am hoping on getting help from someone here. Thank you in advance.
  5 commentaires
bhador
bhador le 6 Mar 2018
The script is not running, it says error. And the answer I'm getting is NaN
Torsten
Torsten le 7 Mar 2018
Modifié(e) : Torsten le 7 Mar 2018
function J = jacobian_numeric(f,x,h)
n = numel(x);
J = zeros(n,n);
for ii = 1:n
hv = zeros(n,1);
hv(ii,1) = h;
J(:,ii) = (f(x+hv) - f(x-hv))./(2*h);
end
end
Wouldn't have happened without implicit expansion ...
Best wishes
Torsten.

Connectez-vous pour commenter.

Réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by