MATLAB Answers

0

I need a code that produce a moving average matrix with a 5*5 window

Asked by safa bousbih on 26 Sep 2017
Latest activity Commented on by safa bousbih on 27 Sep 2017

Hello everyone,

I have an image of 2781 * 1680, and I want to calculate the average of each pixel with a 5 * 5 sliding window that will move throughout the matrix. Knowing that I use matlab 2010 and that I do not have the function movmean.

  0 Comments

Sign in to comment.

2 Answers

Answer by Chad Greene
on 26 Sep 2017
 Accepted Answer

The conv2 function performs 2D convolution of two matrices. One of those matrices is your 2781x1680 dataset, and the other matrix is 5x5 in size.

Convolution works like a weighted moving average. For the sake of simplicity let's talk about a 3x3 moving window. It will look like this:

C = conv2(A,B,'same');  

When convolving some matrix A with a 3x3 matrix B, the value assigned to each pixel will be the sum of the central pixel in A and all eight of its neighboring pixels, but in the 3x3 moving window each pixel in A is multiplied by the corresponding value in B before summing. It's not just a moving average, it's a weighted moving average. If you let B=ones(3,3), the resulting C would be a a 3x3 moving average of A, but would have about 9 times the magnitude of A. You have to divide B by 9 (for a 3x3 moving average) to keep C from having about 9 times the magnitude of A. Run this section of code to see what I mean:

A = peaks(50)+randn(50); 
B = ones(3,3)/3^2; 
C = conv2(A,B,'same'); 
figure
subplot(1,2,1) 
imagesc(A)
axis image
colorbar
subplot(1,2,2) 
imagesc(C) 
axis image
colorbar

Look closely at the values on the colorbar. They're about the same in both images. Some of the highest highs and lowest lows in A have been smoothed out, so the range of values in C is slightly smaller, but still, about the same. Now run the same section of code, but let

B = ones(3,3); 

or for that matter, try

B = 15; 

Note the 'same' option just makes sure the output matrix C is the same size as A.

  1 Comment

Thank you very much Chad. It was clear and helpfull. Thank you again.

Sign in to comment.


Answer by John D'Errico
on 26 Sep 2017
Edited by John D'Errico
on 26 Sep 2017

I'll bet that you do have a simple function that will solve the problem.

Hint:

help conv2

If that is insufficient, then what does

ones(5,5)/25

do for you?

  1 Comment

hello John, I didn't understand the ones(5,5)/25?? Thank you very much

Sign in to comment.


Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today