How can I pivot using if else?
Show older comments
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.
Clarissa Chen
on 2 Oct 2022
Accepted Answer
More Answers (0)
Categories
Find more on Logical 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!