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)
Afficher commentaires plus anciens
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.
Réponses (0)
Voir également
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!