Calculating mean of matrix elements

Hey guys,
I need a bit of help regarding calculating the mean of elements in a matrix. I want to calculate the mean of each value and the eight values surrounding it (excluding elements in the first / last rows and first/ last columns), then display the mean values in a new matrix, with the first / last rows and columns from the original matrix in place. Here is some code that I have put together but cannot seem to get to work:
x = 300x300 matrix
for i = x(2:299, 2:299)
x = [rows, cols];
for rows = 0:255
for cols = 0:255
q = [[rows, cols], [rows-1, cols-1], [rows-1, cols], [rows-1, cols+1], [rows, cols+1], [rows+1, cols-1], [rows+1, cols], [rows+1, cols+1]];
m = mean(q);
end
end
end
n = [m + x(1, 1:300) + x(300, 1:300) + x(1:300, 1) + x(1:300, 300)];

2 Comments

http://www.mathworks.com/matlabcentral/answers/7567-accessing-surrounding-elements-in-an-array
I looked at that page before asking this question and tried the code displayed, but couldn't get it to run properly / produce the correct output. Could you please explain exactly what the code is doing? Thanks

Sign in to comment.

Answers (1)

x = magic(300); %example matrix
x2 = conv2(x,ones(3)/9,'valid'); %windowed mean of 3x3 grid
x(2:end-1,2:end-1) = x2; %insert

Asked:

on 19 May 2011

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!