Why do I get NaN values? How to Fix?

26 visualizaciones (últimos 30 días)
David Velo
David Velo el 25 de Abr. de 2019
Respondida: Walter Roberson el 25 de Abr. de 2019
function x = Gauss2(A,b);
% Solve linear system Ax = b
% using Gaussian elimination without pivoting
% A is an n by n matrix
% b is an n by k matrix (k copies of n-vectors)
% x is an n by k matrix (k copies of solution vectors)
A=[1 0 0 0 0 0 -1 0; 0 -1 0 -1 0 0 0 0; 0 1 -1 0 0 0 0 0; 1 0 0 -1 -1 0 0 0; 0 0 0 0 1 -1 0 0; 0 0 1 0 0 -1 0 0; 0 0 0 0 0 0 -1 0; 0 0 0 0 0 0 1 -1]
b= [35 -50 30 40 20 60 -90 25]'
[n, n] = size(A); % Find size of matrix A
[n, k] = size(b); % Find size of matrix b
x = zeros(n,k); % Initialize x
for i = 1:n-1
m = -A(i+1:n,i)/A(i,i); % multipliers
A(i+1:n,:) = A(i+1:n,:) + m*A(i,:);
b(i+1:n,:) = b(i+1:n,:) + m*b(i,:);
end;
% Use back substitution to find unknowns
x(n,:) = b(n,:)/A(n,n);
for i = n-1:-1:1
x(i,:) = (b(i,:) - A(i,i+1:n)*x(i+1:n,:))/A(i,i);
end

Respuestas (1)

Walter Roberson
Walter Roberson el 25 de Abr. de 2019
rank(A) is 7 rather than 8. At some point in the processing, it will encounter a row whose content can be represented as a linear combination of the prior rows, and at that point, A(i,i) will be 0, and you will get a division by 0. It would be common for there to be 0/0 => nan showing up in these cases.
This is the kind of problem that pivoting is designed to solve, so do not be surprised if they toss a matrix like that in during linear algebra instructions -- to show you that pivoting is needed.

Categorías

Más información sobre Linear Algebra en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by