Index Position 1 is invalid. Newton's method program

When I run the following code, I keep getting errors of either Index Position 1 is invalid or out of range subscript depending on my values for x0. Not sure what to do.
x0=[1,1,1,1,1,1,1,1,1]'; %enter estimates
I defined 9 functions (f1-f9)
J=sym(zeros(9));
for j=1:length(vars) %create Jacobian matrix
J(1,j)=diff(f1,vars(j));
J(2,j)=diff(f2,vars(j));
J(....
end
x=[x0];
for i=1:10
x(:,i+1)=x(:,i)-inv(J(x(1,i),x(2,i),x(3,i),x(4,i),x(5,i),x(6,i),x(7,i),x(8,i),x(9,i)))*f(x(1,i),x(2,i),x(3,i),x(4,i),x(5,i),x(6,i),x(7,i),x(8,i),x(9,i))'; %solve for x
end

 Akzeptierte Antwort

Walter Roberson
Walter Roberson am 20 Mär. 2021
You are invoking J as if it is a function with 9 inputs. But it is not a function: it is a 9 x 9 array of symbolic expressions.
You should create
F = [f1, f2, f3, f4, f5, f6, f7, f8, f9];
Jmat = jacobian(F, vars);
J = matlabFunction(Jmat, 'vars', {vars});
x(:,i) - J(x(:,i))\f(x(1,i),x(2,i),x(3,i),x(4,i),x(5,i),x(6,i),x(7,i),x(8,i),x(9,i))
and easier yet would be if you used matlabFunction() to turn f (whatever it is) into an anonymous function that accepted a vector of inputs.
What is the relationship between f and your f1, f2, and so on?

3 Kommentare

Hi Walter,
So the f1-f9 are symbolic functions that represent a system of equations I'm attempting to solve. f is the entire system of equations put together (this code is trying to execute Newton's method to solve them). When I turn J into a function like you said, I'm getting this error:
Index in position 2 exceeds array bounds (must not exceed 1).
Error in
symengine>@(in1)reshape([0.0,0.0,0.0,-1.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,-1.0,0.0,1.0,1.0,0.0,0.0,0.0,0.0,0.0,0.0,-1.0,-1.0,0.0,1.0,4.0e-2,0.0,0.0,in1(:,4).*-1.0e+5,0.0,0.0,0.0,0.0,0.0,-1.0e-2,1.0e-2,0.0,0.0,in1(:,5).*-1.0e+5,0.0,0.0,0.0,0.0,-1.0e-2,0.0,1.0e-2,0.0,0.0,in1(:,6).*-1.0e+5,0.0,0.0,0.0,0.0,-4.0e-2,4.0e-2,0.0,0.0,0.0,in1(:,7).*-5.0e+4,0.0,0.0,0.0,-1.0e-2,0.0,0.0,0.0,0.0,0.0,in1(:,8).*-1.0e+5,0.0,0.0,0.0,-1.0e-2,0.0,0.0,0.0,0.0,0.0,in1(:,9).*-1.0e+5],[9,9])
Error in CompHW5 (line 44)
x(:,i+1)=x(:,i)-inv(J(x(:,i)))*f(x(:,i))'; %solve for x
Jmat = jacobian(f, vars);
J = matlabFunction(Jmat, 'vars', {vars.'});
x(:,i) - J(x(:,i))\f(x(1,i),x(2,i),x(3,i),x(4,i),x(5,i),x(6,i),x(7,i),x(8,i),x(9,i))
That worked! Thank you so much!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Produkte

Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by