Why do I get an infinity number in matrix X2?

2 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Argument Definitions 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by