简体   繁体   中英

Replace matrix values with mean values extracted from smaller matrix in MATLAB

Let's say I have a 10 x 10 matrix. What I do then is iterate through the whole matrix with an 3 x 3 matrix (except from the edges to make it easier), and from this 3 x 3 matrix I get the mean/average value of this 3 x 3 space. What I then want to do is to replace the original matrix values, with those new mean/average values.

Can someone please explain to me how I can do that? Some code examples would be appreciated.

What you're trying to do is called convolution . In MATLAB, you can do the following (read up more on convolution and how it's done in MATLAB).

conv2( myMatrix , ones(3)/9 , 'same' );

A little deciphering is in order. myMatrix is the matrix you're working on (the 10x10 one you mentioned). The ones(3)/9 command creates a so-called mask of filter kernel , which is

1/9 1/9 1/9
1/9 1/9 1/9
1/9 1/9 1/9

When you take this mask and move it around, multiplying value-by-value the mask's entries with 3x3 entries of the image and then add the results (dot product, essentially), the you get the average of the 9 values that ended up underneath this mask. So once you've placed this mask over every 3x3 segment of you matrix (image, I imagine) and replaced the value in the middle by the average, you get the result of that command. You're welcome to experiment with it further. The 'same' flag simply means that the matrix you're getting back is the same size as you original one. This is important because, as you've yourself realized, there are multiple ways of dealing with the edges.

To do this, you need to keep the original intact until you have got all the means. This means that if you implement this using a loop, you have to store the averages in different matrix. To get the borders too, the easiest way is to copy the original matrix to the new matrix, although only the borders are needed to be copied.

This average3x3 function copies the input Matrix to AveragedMatrix and then goes through all the elements that are not on any border, calculates the mean of 3x3 space and stores it in the corresponding element of AveragedMatrix .

function [AveragedMatrix] = average3x3(Matrix)

AveragedMatrix = Matrix;

if ((size(Matrix, 1) < 3) || (size(Matrix, 2) < 3))
    fprintf('Matrix is too small, minimum matrix size is 3x3.\n');
    return
end

for RowIndex = 2:(size(Matrix, 1)-1)
    Rows = RowIndex-1:RowIndex+1;

    for ColIndex = 2:(size(Matrix, 2)-1)
        Columns = ColIndex-1:ColIndex+1;
        AveragedMatrix(RowIndex,ColIndex) = mean(mean(Matrix(Rows,Columns)));
    end
end

return

To use this function, you can try:

A = randi(10,10);

AveragedA = average3x3(A);

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