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 Kommentare

Andrei Bobrov
Andrei Bobrov am 19 Mai 2011
http://www.mathworks.com/matlabcentral/answers/7567-accessing-surrounding-elements-in-an-array
J.C.
J.C. am 19 Mai 2011
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

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Sean de Wolski
Sean de Wolski am 19 Mai 2011

0 Stimmen

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

Gefragt:

am 19 Mai 2011

Community Treasure Hunt

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

Start Hunting!

Translated by