การสลายตัวของ LU ของเมทริกซ์ทำให้เกิดเมทริกซ์เป็นผลคูณของเมทริกซ์สามเหลี่ยมล่างและเมทริกซ์สามเหลี่ยมบน LU ใน LU การสลายตัวของเมทริกซ์ย่อมาจาก Upper Upper
ตัวอย่างของการสลายตัวของ LU ของเมทริกซ์แสดงไว้ด้านล่าง -
Given matrix is: 1 1 0 2 1 3 3 1 1 The L matrix is: 1 0 0 2 -1 0 3 -2 -5 The U matrix is: 1 1 0 0 1 -3 0 0 1
โปรแกรมที่ดำเนินการ LU Decomposition ของเมทริกซ์แสดงไว้ด้านล่าง -
ตัวอย่าง
#include<iostream>
using namespace std;
void LUdecomposition(float a[10][10], float l[10][10], float u[10][10], int n) {
int i = 0, j = 0, k = 0;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (j < i)
l[j][i] = 0;
else {
l[j][i] = a[j][i];
for (k = 0; k < i; k++) {
l[j][i] = l[j][i] - l[j][k] * u[k][i];
}
}
}
for (j = 0; j < n; j++) {
if (j < i)
u[i][j] = 0;
else if (j == i)
u[i][j] = 1;
else {
u[i][j] = a[i][j] / l[i][i];
for (k = 0; k < i; k++) {
u[i][j] = u[i][j] - ((l[i][k] * u[k][j]) / l[i][i]);
}
}
}
}
}
int main() {
float a[10][10], l[10][10], u[10][10];
int n = 0, i = 0, j = 0;
cout << "Enter size of square matrix : "<<endl;
cin >> n;
cout<<"Enter matrix values: "<endl;
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
cin >> a[i][j];
LUdecomposition(a, l, u, n);
cout << "L Decomposition is as follows..."<<endl;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
cout<<l[i][j]<<" ";
}
cout << endl;
}
cout << "U Decomposition is as follows..."<<endl;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
cout<<u[i][j]<<" ";
}
cout << endl;
}
return 0;
} ผลลัพธ์
ผลลัพธ์ของโปรแกรมข้างต้นมีดังนี้
Enter size of square matrix : 3 Enter matrix values: 1 1 0 2 1 3 3 1 1 L Decomposition is as follows... 1 0 0 2 -1 0 3 -2 -5 U Decomposition is as follows... 1 1 0 0 1 -3 0 0 1
ในโปรแกรมข้างต้น ฟังก์ชันการสลายตัวของ LU ค้นหาการสลายตัวของ L และ U ของเมทริกซ์ที่กำหนด สิ่งนี้ทำได้โดยใช้การซ้อนกันสำหรับลูปที่คำนวณการสลายตัวของ L และ U และเก็บไว้ในเมทริกซ์ l[][] และ u[][] จากเมทริกซ์ a[][].
ข้อมูลโค้ดที่แสดงให้เห็นสิ่งนี้จะได้รับดังนี้ −
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (j < i)
l[j][i] = 0;
else {
l[j][i] = a[j][i];
for (k = 0; k < i; k++) {
l[j][i] = l[j][i] - l[j][k] * u[k][i];
}
}
}
for (j = 0; j < n; j++) {
if (j < i)
u[i][j] = 0;
else if (j == i)
u[i][j] = 1;
else {
u[i][j] = a[i][j] / l[i][i];
for (k = 0; k < i; k++) {
u[i][j] = u[i][j] - ((l[i][k] * u[k][j]) / l[i][i]);
}
}
}
} ในฟังก์ชัน main() ขนาดของเมทริกซ์และองค์ประกอบจะได้รับจากผู้ใช้ ได้ดังนี้ −
cout << "Enter size of square matrix : "<<endl; cin >> n; cout<<"Enter matrix values: "<endl; for (i = 0; i < n; i++) for (j = 0; j < n; j++) cin >> a[i][j];
จากนั้นจะเรียกฟังก์ชันการสลายตัวของ LU และแสดงการสลายตัวของ L และ U แสดงไว้ด้านล่าง -
LUdecomposition(a, l, u, n);
cout << "L Decomposition is as follows..."<<endl;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
cout<<l[i][j]<<" ";
}
cout << endl;
}
cout << "U Decomposition is as follows..."<<endl;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
cout<u[i][j]<<" ";
}
cout << endl;
}