如何在MATLAB中修复此错误:“索引超出矩阵尺寸。”

时间:2015-11-24 21:35:45

标签: matlab math

我试着用MATLAB中的Newton-Raphson方法求解两个带有两个未知数的非线性方程。 这是我的matlab代码:

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

为什么MATLAB显示“索引超出矩阵维度。”?

1 个答案:

答案 0 :(得分:1)

您定义fJ以接收包含两个元素的向量x,但将x初始化为标量:x = 0.01;。将其定义为向量:

x = [0.01;0.01];

此外,对于显示内容的代码部分([iter x'];),我建议使用简单的工作版本

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