Effacer les filtres
Effacer les filtres

Why do I get an infinity number in matrix X2?

1 vue (au cours des 30 derniers jours)
Alexandra Panayiota Gregoriou
Modifié(e) : Torsten le 6 Mar 2022
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

Réponses (2)

Jan
Jan le 5 Mar 2022
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 commentaire
Image Analyst
Image Analyst le 6 Mar 2022
@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.

Connectez-vous pour commenter.


Torsten
Torsten le 6 Mar 2022
Modifié(e) : Torsten le 6 Mar 2022
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.

Catégories

En savoir plus sur Argument Definitions dans Help Center et File Exchange

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by