我正在做一个项目,我需要检查 boolean 数组“vector ”是否与“矩阵”的列线性无关。在 MATLAB 中,可以通过使用命令 rank(gf([矩阵 vector ])) 查找增广矩阵 [矩阵 vector ] 的秩来完成。 'gf' 因为矩阵是 boolean 值。 但是如何在 C++ 中做到这一点。这是我尝试过的:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "engine.h"
#define BUFSIZE 256
int main()
{
Engine *ep;
mxArray *M = NULL, *V = NULL, *result = NULL;
bool matrix[4][4]={1,1,1,0,0,1,1,0,0,1,0,0}, vector[4][1]={1,1,1,1};
double *rank;
if (!(ep = engOpen("\0"))) {
fprintf(stderr, "\nCan't start MATLAB engine\n");
return EXIT_FAILURE;
}
V = mxCreateDoubleMatrix(4, 1, mxREAL);
M = mxCreateDoubleMatrix(4, 4, mxREAL);
memcpy((void *)mxGetPr(V), (void *)vector, sizeof(vector));
memcpy((void *)mxGetPr(M), (void *)matrix, sizeof(matrix));
engPutVariable(ep, "V", V);
engPutVariable(ep, "M", M);
engEvalString(ep, "R = rank(gf([M V]));");
result = engGetVariable(ep, "R");
engClose(ep);
rank = mxGetPr(result);
printf("%f", *rank);
printf("Done with LI\n");
mxDestroyArray(M);
mxDestroyArray(V);
mxDestroyArray(result);
engEvalString(ep, "close;");
}
上面的代码有效,我得到了想要的结果。但是它运行得很慢。任何人都可以建议我一种使其快速的方法吗?或者建议一些其他的方法来找到一个 boolean 矩阵。那里有一些库,但它们似乎只具有用于 int 或 double 矩阵的函数。
最佳答案
您可以通过查找 2 的伽罗瓦域中的秩来求得 boolean 矩阵的秩(就像您在 Matlab 代码中所做的那样),这本质上是模 2 算术。
下面的代码通过使用具有部分主元的高斯消元法,使用相同的想法找到 boolean 矩阵的秩。
#include <iostream>
#include <vector>
using namespace std;
class BooleanMatrix{
vector< vector<bool> > mat; //boolean matrix
int n, m; //size of matrix nxm
int rank; //rank of the matrix
public:
/*Constructor
* Required Parameters:
* M ==> boolean matrix
* n ==> number of rows
* m ==> number of columns
*/
template <size_t size_m>
BooleanMatrix(bool M[][size_m], int n, int m){
this -> n = n;
this -> m = m;
for (int i = 0; i < n; i++){
vector<bool> row(m);
for (int j = 0; j < m; j++) row[j] = M[i][j];
mat.push_back(row);
}
gaussElimination();
}
/* Does Gauss Elimination with partial pivoting on the matrix */
void gaussElimination(){
rank = n;
for (int i = 0; i < n; i++){
if (!mat[i][i]){
int j;
for (j = i+1; j < n && !mat[j][i]; j++);
if (j == n){
rank--;
continue;
}
else
for (int k = i; k < m; k++){
bool t = mat[i][k];
mat[i][k] = mat[j][k];
mat[j][k] = t;
}
}
for (int j = i+1; j < n; j++){
if (mat[j][i]){
for (int k = i; k < m; k++)
mat[j][k] = mat[j][k] - mat[i][k];
}
}
}
}
/* Get the row rank of the boolean matrix
* If you require the rank of the matrix, make sure that n > m.
* i.e. if n < m, call the constructor over the transpose.
*/
int getRank(){
return rank;
}
};
int main(){
bool M1[3][3] = { {1, 0, 1},
{0, 1, 1},
{1, 1, 0} };
BooleanMatrix booleanMatrix1(M1, 3, 3);
cout << booleanMatrix1.getRank() << endl;
bool M2[4][4] = { {1,1,1,0},
{0,1,1,0},
{0,1,0,0},
{1,1,1,1} };
BooleanMatrix booleanMatrix2(M2, 4, 4);
cout << booleanMatrix2.getRank() << endl;
}
对于这两种情况,这都给出了预期的结果。该算法应该适用于所有实际目的。可以根据您的要求进行微不足道的改进和特定于应用程序的更改。
虽然我还没有彻底测试它。如果有人发现任何错误,请编辑答案以更正错误。
希望这对您有所帮助。
关于c++ - 查找 boolean 矩阵的秩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19254711/