我有一個大的2D矩陣A2D,其列秩和行秩總是相等,並且通過4均勻地劃分我想減少兩者列秩和行秩到它們各自的四(1/4)形成另一個矩陣B2D。每個B2D元素是A2D的4×4子矩陣的平均值。爲了解釋清楚我想要做的,我就拿一個簡單的8×8矩陣,並提供您參考下面的代碼片段。我的解決方案非常笨拙。你能否給我展示更好的性能解決方案。先謝謝你。矩陣計算
int arr[8][8] =
{
{11, 12, 13, 14, 15, 16, 17, 18},
{21, 22, 23, 24, 25, 26, 27, 28},
{31, 32, 33, 34, 35, 36, 37, 38},
{41, 42, 43, 44, 45, 46, 47, 48},
{51, 52, 53, 54, 55, 56, 57, 58},
{61, 62, 63, 64, 65, 66, 67, 68},
{71, 72, 73, 74, 75, 76, 77, 78},
{81, 82, 83, 84, 85, 86, 87, 88}
};
int** pColAvg = new int* [8];
for (int i = 0; i < 8; i++)
pColAvg[i] = new int[2];
for (int nRow = 0; nRow < 8; nRow + 4)
{
for (int nCol = 0; nCol < 8; nCol + 4)
{
int Avg = 0;
Avg += arr[nRow][nCol];
Avg += arr[nRow][nCol + 1];
Avg += arr[nRow][nCol + 2];
Avg += arr[nRow][nCol + 3];
Avg /= 4;
pColAvg[nRow][nCol/4] = Avg;
}
}
int** pAvgArray = new int* [2];
for (int i = 0; i < 2; i++)
pAvgArray[i] = new int[2];
for (int nRow = 0; nRow < 8; nRow + 4)
{
for (int nCol = 0; nCol < 2; nCol++)
{
int Avg = 0;
Avg += pColAvg[nRow][nCol];
Avg += pColAvg[nRow + 1][nCol];
Avg += pColAvg[nRow + 2][nCol];
Avg += pColAvg[nRow + 3][nCol];
Avg /= 4;
pAvgArray[nRow/4][nCol] = Avg;
}
}
for (int i = 0; i < 8; i++)
delete [] pColAvg[i];
delete [] pColAvg;
for (int i = 0; i < 2; i++)
delete [] pAvgArray[i];
delete [] pAvgArray;
是它C++還是C? – Wok
是否允許STL? – Wok
@wok:允許使用C++和STL。 – GoldenLee