LU Method

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
public double[,] _Amatrix = new double[,]
{
{ 10, -7, 0 },
{ -3, 6, 2 },
{ 5, -1, 5 }
};
public double[] _Barray = new double[] { 1, 5, 2 };
public double[] _Xarray;
public double[] _Yarray;
public double[,] _Lmatrix = new double[,]
{
{ 1, 0, 0 },
{ 1, 1, 0 },
{ 1, 1, 1 }
};
public double[,] _Umatrix;
public void LU()
{
_Umatrix = new double[_Amatrix.GetLength(0), _Amatrix.GetLength(1)];
_Umatrix = _Amatrix;
int n = _Amatrix.GetLength(0);
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
_Lmatrix[j, i] = _Umatrix[j, i] / _Umatrix[i, i];
}
}
for (int k = 1; k < n; k++)
{
for (int i = k - 1; i < n; i++)
{
for (int j = i; j < n; j++)
{
_Lmatrix[j, i] = _Umatrix[j, i] / _Umatrix[i, i];
}
}
for (int i = k; i < n; i++)
{
for (int j = k - 1; j < n; j++)
{
_Umatrix[i, j] = _Umatrix[i, j] - _Lmatrix[i, k - 1] * _Umatrix[k - 1, j];
}
}
}
}
public void solution()
{
_Yarray = new double[_Barray.Length];
_Xarray = new double[_Barray.Length];
for (int i = 0; i < _Barray.Length; i++)
{
_Yarray[i] = 0;
_Xarray[i] = 0;
}
for (int i = 0; i < _Lmatrix.GetLength(0); ++i)
{
double sum = 0;
for (int k = 0; k < i; ++k)
{
sum += _Lmatrix[i, k] * _Yarray[k];
}
_Yarray[i] = (_Barray[i] - sum) / _Lmatrix[i, i];
}
for (int i = _Umatrix.GetLength(0) - 1; i >= 0; i--)
{
double sum = 0;
for (int k = _Umatrix.GetLength(0) - 1; k >= i; k--)
{
sum += _Umatrix[i, k] * _Xarray[k];
}
_Xarray[i] = (_Yarray[i] - sum) / _Umatrix[i, i];
}
}