简体   繁体   中英

Multidimensional Array 3x3 Average in C

I am stuck with my C-programm where I have to calculate the averages of a multidimensional array by a function.

Let's say you have the following array:

array[5][8];

I am already able to calculate the average of the whole array through a function. But in the exercise you have to calculate the averages of a 3x3 dimensional arrays inside of the 5x8 array and the results have to be written into another array.

It should look something like this

Meaning the 3x3 matrix can overlap.

This is how my function looks so far (it just calculates the sum of the whole matrix). The user can decide the size and values of the array.

void matavg(float *matrixIn, float *matrixOut, int rows, int cols, float *avg) {


float sum = 0;

for (int i = 0; i < rows; i++) {
    for (int j = 0; j < cols; j++) {
        sum += *(matrixIn+i * cols+j);

    }
}


*avg = sum /(rows*cols);

How can I rewrite my function so that only the average of 3x3 elements are consecutively calculated inside of the input array?

*matrixIn is the matrix that is created by the user. *matrixOut should be the matrix with the average values.

Thank you!

//sq - size of the square subarray. 
void matavg3x3(size_t rows, size_t cols, size_t sq, float (*matrixIn)[cols], float (*matrixOut)[sq]) 
{
    for(size_t rowstart = 0; rowstart <= rows - sq; rowstart++)
    {
        for(size_t colstart = 0; colstart <= cols - sq; colstart++)
        {
            double sum = 0.0;
            for(size_t row = 0; row < sq; row++)
            {
                for(size_t col = 0; col < sq; col++)
                {
                    sum += matrixIn[rowstart + row][colstart + col];
                }                
            }
            matrixOut[rowstart][colstart] = sum / (sq * sq);
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM