1

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).

gunr2171
  • 16,104
  • 25
  • 61
  • 88
  • 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](http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab) – Adriaan Nov 14 '15 at 15:20

1 Answers1

1

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.

Sanjay Manohar
  • 6,920
  • 3
  • 35
  • 58