1
votes

I am creating a MATLAB code to estimate the Jacobian matrix using forward differences. Here is the code:

%Calculate Jacobian Numerically using forward differences:
function J=Jacobianest(x,F) % X is a column vector of variables, f is a   column function vector
h=1e-7;
n=length(x);
J=zeros(n);
for i=1:n
    xp=x;
    xp(i)=x(i)+h;
    J(:,i)=1/h*(F(xp)-F(x));
end

When I run it the following error appears:

Jacobianest(x,'multivariable_newton_fun')
Subscript indices must either be real positive integers or logicals.

Error in Jacobianest (line 9)
J(:,i)=1/h*(F(xp)-F(x));

I looked at other questions for answers and tried debugging/dbstop, but I can't seem to find anything obvious.

I am using i as the column index which should just have integer values from 1 to n (all integers hopefully).

1
The error is not in the assignment to J, but in the assignment to F. I guess xp and x are not integers. I think F(xp(i)) would solve your problem. As an additional suggestion: don't use i as a variable - Adriaan

1 Answers

1
votes

You need to pass a function not a string. How about:

Jacobianest(x,@multivariable_newton_fun)

If it's a string, i.e. you use single-quotes, then F(1) gives the first letter of the name the string, in this case 'm'. Also if you try F(0) you'll get the above error.

The @ generates a function (think of a function handle, or a function reference, in other languages). Then the parentheses F(xp) are interpreted as a function call, rather than subscript indices.