简体   繁体   English

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

[英]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. 我正在尝试使用MATLAB中的Newton-Raphson方法求解带有两个未知数的两个非线性方程。 Here is my matlab code: 这是我的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

Why does MATLAB show “Index exceeds matrix dimensions.”? 为什么MATLAB显示“索引超出矩阵尺寸”?

You define f and J to receive a vector x with two elements but initialize x as a scalar: x = 0.01; 您将fJ定义为接收具有两个元素的向量x ,但将x初始化为标量: 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 另外,对于显示内容的代码部分( [iter x']; ),我建议使用一个简单的工作版本作为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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