矩阵sum_矩阵LU分解的MATLAB与C++实现
时间: 2023-11-28 16:05:47 浏览: 117
MATLAB实现:
```matlab
% 矩阵LU分解
function [L,U] = lu_decomposition(A)
n = size(A,1);
L = eye(n);
U = A;
for i=1:n-1
if abs(U(i,i)) < eps
error('Zero pivot encountered');
end
for j=i+1:n
L(j,i) = U(j,i) / U(i,i);
U(j,:) = U(j,:) - L(j,i)*U(i,:);
end
end
end
% 矩阵求和
function S = matrix_sum(A)
S = sum(sum(A));
end
% 测试
A = [1 2 3; 4 5 6; 7 8 9];
[L,U] = lu_decomposition(A);
S = matrix_sum(A);
disp('A=');
disp(A);
disp('L=');
disp(L);
disp('U=');
disp(U);
disp('sum(A)=');
disp(S);
```
C++实现:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 矩阵LU分解
void lu_decomposition(vector<vector<double>>& A, vector<vector<double>>& L, vector<vector<double>>& U)
{
int n = A.size();
L = vector<vector<double>>(n, vector<double>(n, 0));
U = A;
for(int i=0;i<n-1;i++)
{
if(abs(U[i][i]) < 1e-6)
{
throw "Zero pivot encountered";
}
for(int j=i+1;j<n;j++)
{
L[j][i] = U[j][i] / U[i][i];
for(int k=i;k<n;k++)
{
U[j][k] -= L[j][i] * U[i][k];
}
}
}
for(int i=0;i<n;i++)
{
L[i][i] = 1;
}
}
// 矩阵求和
double matrix_sum(vector<vector<double>>& A)
{
double S = 0;
for(int i=0;i<A.size();i++)
{
for(int j=0;j<A[0].size();j++)
{
S += A[i][j];
}
}
return S;
}
// 测试
int main()
{
vector<vector<double>> A{{1,2,3},{4,5,6},{7,8,9}};
vector<vector<double>> L,U;
lu_decomposition(A,L,U);
double S = matrix_sum(A);
cout << "A=" << endl;
for(auto row:A)
{
for(auto ele:row)
{
cout << ele << " ";
}
cout << endl;
}
cout << "L=" << endl;
for(auto row:L)
{
for(auto ele:row)
{
cout << ele << " ";
}
cout << endl;
}
cout << "U=" << endl;
for(auto row:U)
{
for(auto ele:row)
{
cout << ele << " ";
}
cout << endl;
}
cout << "sum(A)=" << S << endl;
return 0;
}
```
阅读全文