【墨鰲】【逆矩陣】【行列式】
阿新 • • 發佈:2022-06-01
概念
先版個板子
#include <bits/stdc++.h> using namespace std; class Matrix{ private: vector<vector<double>>a; public: void show(){ for(auto row:a){ for(auto v:row) cout<<v<<" "; cout<<endl; } } int cols(){ return a.size(); } int rows(){ return a[0].size(); } int get(int x,int y){ return a[x][y]; } void set(int x,int y,int val){ a[x][y]=val; } // 空矩陣 Matrix(int n,int m):a(n,vector<double>(m,0)){ } // 單位矩陣 Matrix(int n):a(n,vector<double>(n,0)){ for(int i=0;i<n;i++)a[i][i]=1; } // 拷貝構造 Matrix(vector<vector<double>>&b){ int n=b.size(),m=b[0].size(); a=vector<vector<double>>(n,vector<double>(m,0)); for(int i=0;i<n;i++) for(int j=0;j<m;j++) if(b[i][j])a[i][j]=b[i][j]; } // 代數餘子式 A(i,j) Matrix remove(int x,int y){ int n=rows()-1,m=cols()-1; Matrix B(n,m); for(int i=0;i<n;i++) for(int j=0;j<m;j++) B.set(i,j,get(i+(i>=x),j+(j>=y))); return B; } // 矩陣轉置 Matrix T(){ int n=cols(),m=rows(); Matrix B(n,m); for(int i=0;i<n;i++) for(int j=0;j<m;j++) B.set(i,j,get(j,i)); return B; } // 矩陣數乘 void mul(double x){ for(auto&row:a)for(auto&v:row)v*=x; } }; // 求行列式 n ×n double det(Matrix A){ int n=A.rows(); if(n==1)return A.get(0,0); double sum=0; for(int j=0;j<n;j++) sum+=A.get(0,j)*det(A.remove(0,j))*(j%2?-1:1); return sum; } // 矩陣乘法 Matrix multiply(Matrix&A,Matrix&B){ int n=A.rows(),m=B.cols(); Matrix C(n,m); int K=A.cols()!=B.rows()?-1:A.cols(); for(int i=0;i<n;i++) for(int j=0;j<m;j++) for(int k=0;k<K;k++) C.set(i,j,C.get(i,j)+A.get(i,k)*B.get(k,j)); return C; } Matrix company_matrix(Matrix&A) { int n=A.cols(); Matrix B(n,n); for(int i=0;i<n;i++) for(int j=0;j<n;j++) B.set(j,i,det(A.remove(i,j))*((i+j)%2?-1:1)); return B; } int main(){ vector<vector<double>> mat1{ {5,0,0,-3}, {0,3,1,0}, {0,4,-2,0}, {1,0,0,2} }; Matrix A(mat1); puts("矩陣A"); A.show(); cout<<endl; Matrix A1=company_matrix(A); puts("伴隨矩陣"); A1.show(); cout<<endl; double detA=det(A); cout<<"det A = "<<detA<<endl; cout<<endl; Matrix I=multiply(A,A1); I.mul(1.0/detA); I.show(); cout<<endl; //cout<<det(A)<<endl; return 0; }