Why do I get an infinity number in matrix X2?

3 ビュー (過去 30 日間)
Alexandra Panayiota Gregoriou
Alexandra Panayiota Gregoriou 2022 年 3 月 5 日
編集済み: Torsten 2022 年 3 月 6 日
I am using the Jacobi method in matlab but when I run the program the matrix X2 seems to have a problem. I think its something to do with the while loop?
My program in the editor is
A=[2 -1 1; 3 -3 9; 3 3 5];
B=[7; 18; 14];
X1=[1; 0; 0];
s=3;
X2=zeros(3,1);
i=1;
j=i;
X3=rand(3,1);
while X2~=X3
for i=1:s
sum=0;
if X2~=X3
for j=1:s
if i~=j
sum=sum+A(i,j)*X2(j,1);
end
end
X3(i,1)=(1/A(i,i))*(B(i)-sum);
end
end
X2=X3;
X3=ones(3,1);
end
X1
X2
X3
Plsss help me I have to submit this assignment asap

回答 (2 件)

Jan
Jan 2022 年 3 月 5 日
X3 is growing massively until it reachs Inf. Simply insert some output, e.g. by removing the semicolon from "X2=X3;" to observe this.
This happens, because this is, what the code instructs Matlab to do. I cannot recommend a fixing, because I do not know, what you want to calculate instead.
  1 件のコメント
Image Analyst
Image Analyst 2022 年 3 月 6 日
@Alexandra Panayiota Gregoriou, Also, don't use "sum" as the name of your variable since it's the name of an important built-in function. Call it "theSum" or something else.

サインインしてコメントする。


Torsten
Torsten 2022 年 3 月 6 日
編集済み: Torsten 2022 年 3 月 6 日
function main
%A = [2 -1 1; 3 -3 9; 3 3 5];
%b = [7; 18; 14];
%x0 = [1; 0; 0];
A = [4 -1 -1; -2 6 1; -1 1 7];
b = [3; 9; -6];
x0 = [0; 0; 0];
Eps = 1e-8;
x = JacobiSolve(A, b, x0, Eps);
x
A*x-b
end
function x = JacobiSolve(A, b, x0, Eps)
n = length(b) ;
x = zeros(size(x0));
Error = 1;
while Error >= Eps
for i = 1 : n
x(i) = b(i) ;
for j = 1 : n
if j ~= i
x(i) = x(i) - A(i, j)*x0(j) ;
end
end
x(i) = x(i) / A(i, i) ;
end
Error = norm(x-x0, inf);
x0 = x;
end
end
Note that the Jacobi method is not guaranteed to converge for every matrix A.

カテゴリ

Help Center および File ExchangeSoftware Development Tools についてさらに検索

製品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by