比较两个矩阵的有趣算法

Interesting algorithm to compare two matrices?

本文关键字:算法 两个 比较      更新时间:2023-10-16

我有一个问题,基本上,我有两个矩阵(向量),一个大矩阵和一个较小的矩阵。我有一个算法,可以将大块矩阵分成块(小块的大小)

例如(我在这里使用测试数据),所以大矩阵大小是:4x4,小矩阵是 2x2,然后我将特定块(在当前位置)传递给一个函数,该函数检查小矩阵是否等于大块(在该特定位置)如果是, 然后返回 true,否则返回 false。

我可以像这样输出每个块:

bool compareMatrix(vector<double> &theMatrix1, vector<double> &theMatrix2, int startRow, int startCol)
{
      // I can output the matrix blocks like this:
      cout << theMatrix1[startRow*2+startCol] << endl;    
}

但我不太明白如何将块(在 startingRow/Col 处)与小矩阵进行比较。

怎么会是这样的:矩阵 1:(4x4)

0 1 0 1 
1 1 0 1 
0 0 1 1 
0 1 1 1

矩阵 2:(2x2)

0 1 
0 1

然后,我将块分成 2x2:

B1 =

0 1 
1 1

是 B1 等于矩阵 2 - 否,所以返回假

B2 =

0 1
0 1

是 B2 等于矩阵 2 - 是的,所以返回 true

我真的试图尽可能详细地解释事情,并希望有人能给我一些建议,因为我已经为此工作了很长时间!

谢谢

如果知道大矩阵的大小,你可以像这样将它的小部分与 2x2 矩阵进行比较

int bigMatrixSize=4;
bool compare(...)
{
 for (int i=0; i<2; ++i)
    for (int k=0; k<2; ++k)
       if(bigMatrix[k+startX+(i+staryY)*bigMatrixSize] != smallMatrix[k][i])
           return false;
 return true;
}

我省略了边界检查和其他一些东西,但它应该给你一个想法。

bool compareMatrix(vector<double> &theMatrix1, int nRow1, int nCol1, vector<double> &theMatrix2, int nRow2, int nCol2, int startRow, int startCol)
{
    int p1 = startRow * nCol1 + startCol, p2 = 0;
    for (int y = 0; y < nRow2; ++y)
    {
        for (int x = 0; x < nCol2; ++x)
        {
            if (theMatrix1[p1 + x] != theMattrix2[p2 + x]) // You can use memcmp here, but it's safer let compiler do the optimization.
            {
                return false;
            }
        }
        p1 += nCol1;
        p2 += nCol2;
    }
    return true;
}

你想要这样的东西吗?您可以将列计数添加到位置以到达下一行。