gauss elimination back substitution
102 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponses (1)
Ravi
le 15 Déc 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
0 commentaires
Voir également
Catégories
En savoir plus sur Polynomials dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!