Problem in implementing Echelon Form and Solve System of Linear Equations

3 次查看(过去 30 天)
Here is my code:
A = [3 2 1;-4 5 7;1 0 -9];
b = [1;4;5];
% Solving System of Linear Equations by using built-in command for inverse
% method
x1 = A\b;
disp(x1);
-0.3636 1.3434 -0.5960
[m,n]=size(A);
x=zeros(n,1);
% Solving System of Linear Equations by using Echelon Form Method
% Matrix reduced to Echelon Form
for j=1:min(m,n)
x(j)=b(j)/A(j,j);
A(j,:) = A(j,:)/A(j,j);
for i = j+1:m
A(i,:)= A(i,:)- A(j,:)*A(i,j);
end
end
% Backward Substitution
for k=n:-1:1
if (A(k,k)==0)
error('Matrix is singular!');
end
b(1:k-1)=b(1:k-1)-A(1:k-1,k)*x(k);
end
disp(x)
0.2899 -1.4348 5.0000
But I am getting wrong result in implementing Echelon Form Method. Please help me to figure out the error. Possilbly the error lies in backward substitution, but didn't understand how to get rid of.

回答(1 个)

Nikhil
Nikhil 2022-10-26
Hi Usman, the following code works for me. I first converted into upper triangular and did backward sub.
A = [3 2 1;-4 5 7;1 0 -9];
B = [1;4;5];
[m,n] = size(A);
x = zeros(m,1);
for i = 1:m-1
factor = A(i+1:m,i)/A(i,i);
% i = 1 => factors = A(2,1)/A(1,1) & A(3,1)/A(1,1) short note % A(2:3,1)/A(1,1)
A(i+1:m,:) = A(i+1:m,:) - factor*A(i,:);
% making non-diagonal elements zero
% in this case -4 = -4 - (-4/3)*3
% for first iteration A(2,1) AND A(3,1) become zero
% second iteration A(3,2) becomes zero
B(i+1:m,:) = B(i+1:m,:) - factor*B(i,:);
end
% now we have upper triangular matrix
% so z value = b(3)/a(3,3)
% and keep doing backward sub
x(m,:) = B(m,:)/A(m,m);
for i = m-1:-1:1
x(i,:) = (B(i,:) - A(i,i+1:m)*x(i+1:m,:))/A(i,i);
end
x

类别

Help CenterFile Exchange 中查找有关 Linear Algebra 的更多信息

产品

Community Treasure Hunt

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

Start Hunting!

Translated by