Use crout method to find L and U, then use L and U to obtain a solution

27 visualizzazioni (ultimi 30 giorni)
function [L,U]=LU_Crout(A,c) %Function to carryout LU factorization using Crout's Algorithm
m=length(A);
n = length(c);
L=zeros(size(A));
U=zeros(size(A));
L(:,1)=A(:,1);
U(1,:)=A(1,:)/L(1,1);
U(1,1)=1;
for k=2:m
for j=2:m
for i=j:m
L(i,j)=A(i,j)-dot(L(i,1:j-1),U(1:j-1,j))
end
U(k,j)=(A(k,j)-dot(L(k,1:k-1),U(1:k-1,j)))/L(k,k)
end
d(1,1) = c(1,1)/L(1,1);
for j = 2:n
for i = j:n
d(i,1) = (c(i,1) - dot(L(i,1:j-1),d(i,1)))/L(i,i);
end
end
end
end
  2 Commenti
Quinten
Quinten il 15 Set 2016
I can't figure out where I'm going wrong when I attempt the forward substitution.
John D'Errico
John D'Errico il 15 Set 2016
BTW, using the length function on an array is a dangerous thing. I'd strongly suggest you avoid that, as it will cause problems for you in the future.

Accedi per commentare.

Risposte (1)

John D'Errico
John D'Errico il 15 Set 2016
Modificato: John D'Errico il 15 Set 2016
(Again, use of length on an array is a dangerous thing, asking for buggy code in the future.)
First, I would suggest testing the code to make sure that it forms the correct arrays, L & U.
A = rand(4,4)
A =
0.67874 0.65548 0.27692 0.69483
0.75774 0.17119 0.046171 0.3171
0.74313 0.70605 0.097132 0.95022
0.39223 0.031833 0.82346 0.034446
L*U
ans =
0.67874 0.65548 0.27692 0.69483
0.75774 0.17119 0.046171 0.3171
0.74313 0.70605 0.29774 0.75124
0.39223 0.031833 -0.0027364 0.11769
It looks pretty close. But is it?
A - L*U
ans =
0 0 0 1.1102e-16
0 0 0 0
0 0 -0.20061 0.19898
0 0 0.82619 -0.083244
So you screwed up in your computation of L and U. That is where you should look FIRST. Where you see the errors in that product should probably even point out where to look in your code.
Hint: When you write a piece of code, don't just write the entire thing, then run it and hope it will work. Instead, test EVERY fragment to verify that it does what you expect. If you do so, then when you run the entire thing, you will often find that now it works on the first pass, because you know that every piece is correct.
  2 Commenti
Quinten
Quinten il 19 Set 2016
My computation of L and U works every time. It's my computation to obtain a solution to find x1 x2 and x3 that is wrong
John D'Errico
John D'Errico il 19 Set 2016
In the test case I ran, it appears your code did not in fact run correctly as the product of L*U shows there. Sadly, I don't have the original matrices, only the printed approximations as reported, so I cannot test to see what happened.
Regardless, the loop at the end uses only L, not U. So if you are trying to solve a linear system, you need to do TWO substitutions, a back subs and a forward subs.

Accedi per commentare.

Categorie

Scopri di più su Linear Algebra in Help Center e File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by