How can I pivot using if else?
10 views (last 30 days)
Show older comments
Clarissa Chen
on 2 Oct 2022
Commented: Walter Roberson
on 3 Oct 2022
I have an assignment which requires me to write a general function that can handle any number of unknowns for Gauss Elimination. I have already written a code but I am wondering how do I write it in a way where if the first element of the first row and column is zero to carry on with the pivoting but if it's not a 0 then continue with the Gauss Elimination? Below is my code:
function[x,y,z] = Question2(a,b)
C=[a b]; %Augmented Matrix
if C(1,:)==0
C([1 3],:)=C([3 1],:); %Pivoting R1 with R3
else
%Upper Triangular Matrix
C(2,:) = C(2,:) - (C(2,1)*C(1,:)/C(1,1));
C(3,:)=C(3,:) - (C(3,1)*C(1,:)/C(1,1));
C(3,:)=C(3,:) - (C(3,2)*C(2,:)/C(2,2));
%Back Substitution
z=C(3,4)/C(3,3);
y=(C(2,4)-z*C(2,3))/C(2,2);
x=(C(1,4)-z*C(1,3)-y*C(1,2))/C(1,1);
end
end
2 Comments
Walter Roberson
on 2 Oct 2022
Note that you talk about "any number" but you do not test before assuming that the matrix has 3 rows or 4 columns.
Accepted Answer
Walter Roberson
on 2 Oct 2022
If you
[row, col, pv] = find(C,1);
then if row is empty then the entire C matrix is 0; otherwise pv would be the pivot value and C(row,col) is the location of the pivot value.
Then, if row is not the same as the iteration number but col is the same as the iteration number, then exchange that row with the row matching the iteration number. If row is not the same as the iteration number but col is greater than the iteration number, the implication is that you have a column that has become zero, and you have to do the appropriate thing for that case... possibly exchange columns.
6 Comments
Walter Roberson
on 3 Oct 2022
Suppose that n is your iteration number. Then under the assumption that you have already rearraged C for the iterations before n, then
[row, col, pv] = find(C(n:end, n:end), 1);
row = row + n - 1; col = col + n - 1;
Now row and col are the locations in C where the next pivot value is to be found -- examining only the rows and columns "below and to the right" of where you are currently examining.
Then examine col: if col is not equal to n, then there are no non-zeros in the current column, and you need to do a column exchange between column n and column col to move the first column to the right with non-zero entries over to the column you are paying attention to. After that, if row is not equal to n, then exchange rows n and row . Once those column and row exchanges are done, then the pivot value will be at row n column n.
(Make sure you test that row and column are not empty -- the case where there are no more non-zero values "below and right" in the array.)
More Answers (0)
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!