gauss elimination back substitution

102 Ansichten (letzte 30 Tage)
saphir alexandre
saphir alexandre am 8 Apr. 2022
Beantwortet: Ravi am 15 Dez. 2023
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 Kommentare
Torsten
Torsten am 8 Apr. 2022
What if A(j,j) = 0 for at least one j ?
saphir alexandre
saphir alexandre am 8 Apr. 2022
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);

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Ravi
Ravi am 15 Dez. 2023
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

Kategorien

Mehr zu Polynomials finden Sie in Help Center und File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by