簡體   English   中英

如何在MATLAB中解決此錯誤:“索引超出矩陣尺寸。”

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

我正在嘗試使用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顯示“索引超出矩陣尺寸”?

您將fJ定義為接收具有兩個元素的向量x ,但將x初始化為標量: x = 0.01; 將其定義為向量:

x = [0.01;0.01];

另外,對於顯示內容的代碼部分( [iter x']; ),我建議使用一個簡單的工作版本作為

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM