matlab下的挺慢,所以先用C++写了简单的矩阵运算
目前只有行列式计算功能
通过 class Matrix实现
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int cntInv(const vector<int>& nums) {
int inversions = 0;
for (int i = 0; i < nums.size(); ++i) {
for (int j = i + 1; j < nums.size(); ++j) {
if (nums[i] > nums[j]) {
inversions++;
}
}
}
return inversions;
}
void genPerm(int n, vector<vector<int>>& permutations, vector<int>& inversions) {
vector<int> nums;
for (int i = 1; i <= n; ++i) {
nums.push_back(i);
}
do {
permutations.push_back(nums);
inversions.push_back(cntInv(nums));
} while (next_permutation(nums.begin(), nums.end()));
}
class Matrix {
public:
int i, j;
int det = 0;
vector<vector<int>> val;
Matrix(int row, int col) : i(row), j(col), val(row, vector<int>(col)) {}
void valSet(vector<int> input) {
int cnt = 0;
for (int row = 1; row <= i; ++row) {
for (int col = 1; col <= j; ++col) {
val[row - 1][col - 1] = input[cnt];
cnt++;
}
}
}
void detCal() {
j = i;
vector<vector<int>> perms;
vector<int> invs;
genPerm(i, perms, invs);
for (int k = 0; k < perms.size(); ++k) {
int temp = 1;
for (int row = 1, t = 0; row <= i && t < i; ++row, ++t) {
temp *= val[row - 1][perms[k][t] - 1];
}
det += pow(-1, invs[k]) * temp;
}
}
};
void display(){
cout<<"Function list\n";
cout<<"1.Calculate determinant\n";
}
int main() {
int num=0;
cout<<"Input matrix num:";
cin>>num;
switch(num){
case 1:{
cout<<"Input A(mxn):\n" ;
int i,j=0;
cout<<" m=";cin>>i;
cout<<" n=";cin>>j;
Matrix A(i,j);
vector<int> input;
cout<<"Input matrix\n";
for(int k=0;k<i*j;k++){
int temp=0;
cin>>temp;
input.push_back(temp);
}
A.valSet(input);
cout<<endl;
display();
int commend=0;
cin>>commend;
switch (commend) {
case 1:{
A.detCal();
cout<<endl<<"det(A)= "<<A.det;
}
}
}
}
return 0;
}