gauss elimination back substitution

조회 수: 102 (최근 30일)
saphir alexandre
saphir alexandre 2022년 4월 8일
답변: Ravi 2023년 12월 15일
Hello,
I am typing a function for the gauss elimination process
I have everything up until the top triangle
I have found a way to do the back substitution using 1 for loop and 1 line of code, but my teacher wants us to use 2 nested for loops
here is what i have so far
function [x] = gauss_elim(A,b)
[n,~] = size(b);
x = zeros(n,1);
Aaug=[A b];
for j=1:n-1
pivot = Aaug(j,j);
for i=j+1:n
nRow(j,:) = (Aaug(i,j) / pivot);
Aaug(i,:) = Aaug(i,:)- nRow(j,:);
end
end
%this part is the back sub, I used only the 1st for loop
x(n, :)=Aaug(n,n+1:end)/Aaug(n,n);
for i=n-1:-1:1
for k = n-j:1 %how do i implement this second loop?
x(i) = (Aaug(i,n+1) - Aaug(i,i+1:n)*x(i+1:n,:))/Aaug(i,i); % this is the single line i wrote
end
end
end
  댓글 수: 2
Torsten
Torsten 2022년 4월 8일
What if A(j,j) = 0 for at least one j ?
saphir alexandre
saphir alexandre 2022년 4월 8일
I wrote a line to move the row with the maximum value in the augmented matrix as the top row, under the for j = 1:n-1
[maxval,row] = max( abs(Aaug(j:n,j)));
if Aaug(1,1)~= maxval
savedAaug1row = Aaug(j,:);
Aaug(j,:) = Aaug(row,:);
Aaug(row,:) = savedAaug1row;
end
pivot = Aaug(j,j);

댓글을 달려면 로그인하십시오.

답변 (1개)

Ravi
Ravi 2023년 12월 15일
Hi Saphir Alexandre,
I could understand you are facing an issue in using the second for loop. Please find the potential solution for the same.
% Back substitution
for i = n:-1:1
% Initialize sum
sum = 0;
for j = i+1:n
sum = sum + Aaug(i,j) * x(j);
end
% Calculate the value of x at the ith position
x(i) = (Aaug(i,end) - sum) / Aaug(i,i);
end
The outer loop starts at the last row of the augmented matrix and moves towards the first row. This is done in reverse because the last row of the matrix contains only one unknown and can be solved directly.
The second loop is necessary to compute the sum of products of coefficients and variable values that are solved from the bottom rows of the matrix. This loop starts from the column just to the right of the diagonal element (“j = i+1”) and goes to the last column of the coefficients (“j = n”). This sum represents the part of the equation that has already been solved in the rows below.
After calculating the sum, we can find the solution for the current variable “x(i)”. This is done by subtracting the sum from the augmented part of the row (“Aaug(i,end)”), which represents the constant term “b(i)”, and then dividing by the diagonal coefficient (“Aaug(i,i)”). This gives us the value of the current variable.
Hope this helps.
Thanks,
Ravi Chandra

카테고리

Help CenterFile Exchange에서 Polynomials에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by