-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLU_Decomposition.c
83 lines (70 loc) · 1.82 KB
/
LU_Decomposition.c
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
#include <stdio.h>
#define MAX_SIZE 100
void printMatrix(double matrix[MAX_SIZE][MAX_SIZE], int n)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
printf("%.6lf\t", matrix[i][j]);
}
printf("\n");
}
}
int luDecomposition(double A[MAX_SIZE][MAX_SIZE], double L[MAX_SIZE][MAX_SIZE], double U[MAX_SIZE][MAX_SIZE], int n)
{
for (int i = 0; i < n; i++)
{
for (int k = i; k < n; k++)
{
double sum = 0.0;
for (int j = 0; j < i; j++)
{
sum += L[i][j] * U[j][k];
}
U[i][k] = A[i][k] - sum;
}
for (int k = i; k < n; k++)
{
if (i == k)
{
L[i][i] = 1.0;
}
else
{
double sum = 0.0;
for (int j = 0; j < i; j++)
{
sum += L[k][j] * U[j][i];
}
L[k][i] = (A[k][i] - sum) / U[i][i];
}
}
}
return 1; // Success
}
int main()
{
int n;
printf("Enter the size of the square matrix: ");
scanf("%d", &n);
double matrix[MAX_SIZE][MAX_SIZE];
printf("Enter the elements of the matrix:\n");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
scanf("%lf", &matrix[i][j]);
}
}
double L[MAX_SIZE][MAX_SIZE] = {0}; // Initialize L matrix
double U[MAX_SIZE][MAX_SIZE] = {0}; // Initialize U matrix
if (luDecomposition(matrix, L, U, n))
{
printf("Lower Triangular (L) Matrix:\n");
printMatrix(L, n);
printf("Upper Triangular (U) Matrix:\n");
printMatrix(U, n);
}
return 0;
}