MATLAB: Computing a Jacobian Numerically using 5pt stencil approximation

jacobian

Hi guys! I am trying to compute a jacobian numerically using a 5-pt stencil approximation. my array F contains two functions:
x = [x1;x2];
f = @(x1,x2) func1(x);
g = @(x1,x2) func2(x);
%Assigning functions to an array
F(1,1) = {f};
F(2,1) = {g};
Then, I am trying to compute my jacobian but am not getting proper results.
function [J,h] = jacob(F,x)
[n,m] = size(x);
h = zeros(n,1);
%Initialize Jacobian
J = zeros(n,n);
%Numerical computation of Jacobian using 5-pt stencil approximation
for i = 1:n
for j = 1:m
%If i == j, h takes the value of the step size
if i == j
h(i) = 1e-3;
end
J(i,j) = (F{i,1}(x(j)+2*h(j)) + 8*F{i,1}(x(j)+h(j)) - 8*F{i,1}(x(j)-h(j)) + F{i,1}(x(j)-2*h(j)))/(12*h(j));
h(j) = 0;
end
end
end

Best Answer

f = @(x1,x2) func1([x1,x2]);
g = @(x1,x2) func2([x1,x2]);
However, in your code you invoke
F{i,1}(x(j)+2*h(j))
so you carefully defined a function handle to take two values, but you are passing in only one value.
Related Question