0
votes

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.”?

1
Your functions J and f use x(2), while you call them with a scalar x. There is no x(2). - Andras Deak
Thanks in advance :) - asghar

1 Answers

1
votes

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