简体   繁体   中英

How can I fix this error in MATLAB: “Index exceeds matrix dimensions.”

I'm tryin to solve two non-linear equations with two unknowns with the Newton-Raphson method in MATLAB. Here is my matlab code:

f = @(x)[ x(1)^2+x(2)^2;
          2*x(1)-x(2)];
J = @(x)[ 2*x(1), 2*x(2);
          2, -1];
tol = 1e-4; % Or some other tolerance
err = 1000; % Any value larger than tol
x = 0.01; % However this is defined.
iter = 1; max_iter = 30; % Or whatever.
while (err > tol)
    delta_x = J(x)\(-f(x)); % Compute x_{n+1}-x_n
    err = norm(delta_x);
    x = x + delta_x;
    iter = iter + 1;
    [iter x']; % This line simply outputs the current iteration and the solution. You can dress this up by using sprintf if you like.
    if (iter > max_iter)
        disp 'Failed to converge';
        break;
    end
end

Why does MATLAB show “Index exceeds matrix dimensions.”?

You define f and J to receive a vector x with two elements but initialize x as a scalar: x = 0.01; . Define it as a vector:

x = [0.01;0.01];

Also, for the portion of the code displaying stuff ( [iter x']; ), I'd suggest a simple working version as

disp(['iter: ',num2str(iter)]);
disp(x.');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM