C++矩阵运算(简易版,不一定会更新)

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;
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值