使用 C++ 程式執行任何矩陣的 LU 分解
矩陣的 LU 分解建立一個矩陣,即其下三角陣和上三角陣的乘積。矩陣 LU 分解中的 LU 代表下三角陣和上三角陣。
下面提供矩陣 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 分解的程式 −
示例
#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 分解。這是透過使用巢狀 for 迴圈完成的,該迴圈計算 L 和 U 分解,並將它們儲存在矩陣 a[][] 的 l[][] 和 u[][] 矩陣中。
展示此功能的程式碼片段如下 −
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;
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP