Gauss/full pivoting problem help
3 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Hey all--
I'm working on a hmwk assignment where we use complete pivoting and Cramer's rule to solve for a vector of unknowns, starting with a square matrix A and solution vector b. I'm then supposed to compare it to Matlabs built-in left-divide function (A\b). My results are not close enough to the Matlab solution so I know I must have something wrong in my code. However I'm not sure where the error is, but I think its in my first "for" loop.
any pointers would be appreciated
here is the code for the main program -- the cramers rule function was given to us and so I know it works. I've pasted the cramers rule code just in case anyone wants to run it. thanks!!!
clc
clear
%define A b and x_ord
A=[8 -2 -1 0 0;
-2 9 -4 -1 0;
-1 -3 7 -1 -2;
0 -4 -2 12 -5;
0 0 -7 -3 15];
b=[5 2 1 1 5]';
sln=A\b;
x_ord=[1:length(b)]';
%define augmented matrix C
C=A;
C(:,end+1)=b;
[nrC,ncC]=size(C);
for i=1:nrC
pivotval=max(max(abs(C(i:nrC,i:nrC))));
[m,n] = find(abs(C(i:nrC,i:nrC)) == pivotval);
p=m+(i-1); %adjusted row position wrt C
q=n+(i-1); %adjusted column position wrt C
%swapping rows
oldrow=C(i,i:ncC);
C(i,i:ncC)=C(p,i:ncC);
C(p,i:ncC)=oldrow;
%swapping columns
oldcol=C(i:nrC,i);
C(i:nrC,i)=C(i:nrC,q);
C(i:nrC,q)=oldcol;
%swap x ord
oldord=x_ord(i);
x_ord(i)=x_ord(q);
x_ord(q)=oldord;
end
CA=C(1:nrC,1:(end-1));
Cb=C(1:nrC,end);
Cx=Cramers_rule(CA,Cb);
r=length(Cx);
fprintf('Original Order Shifter Order\nLeft Division Cramers Rule\n')
fprintf('************************************\n')
for i=1:r
fprintf(' x(%d) = %.3f | x(%d) = %.3f\n',i,sln(i),i,Cx(i))
end
fprintf('************************************\n')
%Cramers Rule function program
function x = Cramers_rule(A,b)
[nra,nca]=size(A);
DA=det(A);
for i =1:nra
C= A;
C(:,i)=b;
x(i)=det(C)/DA;
end
0 comentarios
Respuestas (0)
Ver también
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!