Your code seems to work fine from what I can tell, at least for the basic examples A=[1,2;3,4]
or A=[3,4;1,2]
. Change your function definition to:
function [L,U,P] = newgauss(A)
so you can output your calculated values (much better than using disp
, but this shows the correct results too). Then you'll see that P*A = L*U
. Maybe you were expecting L*U
to equal A
directly? You can also confirm that you are correct via Matlab's lu
function:
[L,U,P] = lu(A);
L*U
P*A
Permutation matrices are orthogonal matrices, so P−1 = PT. If you want to get back A
in your code, you can do:
P'*L*U
Similarly, using Matlab's lu
with the permutation matrix output, you can do:
[L,U,P] = lu(A);
P'*L*U
(You should also use error
or warning
rather than how you're using disp
in checking the determinant, but they probably don't teach that.)