Matrix calculation
I have a large 2D matrix A2D, which the column rank and the row rank are always equal, and evenly divided by 4. I want to reduce both the column rank and the row rank to their respective quater (1/4) to form another matrix B2D. Each B2D element is an average of 4x4 sub-matrix of A2D. To account for clearly what I want to do, I take a simple 8x8 matrix for example, and provide the following code snippet for your reference. My solution is very clumsy. Would you please show me aother solution with better performance. Thank you in advance.
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开发者_如何学Python; 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;
I think that your solution can be incorrect (even if by average you mean floor of exact average). Here is my solution:
int** solveIt(int **arr, int n){
int **result = new int*[n/4];
for(int i=0; i<n; i+=4){
result[i] = new int[n/4];
for(int j=0; j<n; j+=4){
int sum = 0;
for(int k=0; k<4; k++)
for(int q=0; q<4; q++)
sum += arr[i+k][j+q];
result[i/4][j/4] = sum/16;
}
}
return result;
}
this is function that takes array and size of that array, and returns result array.
Edit: and the example where your solution doesn't work:
1 1 1 1
1 1 1 2
1 1 1 1
1 1 0 1
The answer is:
1
but your solution will give:
0
精彩评论