Average of the nine surrounding cells

3 Ansichten (letzte 30 Tage)
Ahmed Abdulla
Ahmed Abdulla am 29 Mai 2020
Kommentiert: Stephen23 am 29 Mai 2020
I have two matrices, matrix1 contains genuine data and matrix2 is filled with 0's and a few 1's, i wanted to know if there is a way to calculate the average of all 9 cells surrounding the cell with the 1 in the matrix with the genuine data. i.e when a 1 is spotted in matrix2 then the average of the 9 surrounding cells to the corresponsinding cell in matrix1 is calculated.
Im not sure if this is clear

Akzeptierte Antwort

Stephen23
Stephen23 am 29 Mai 2020
Bearbeitet: Stephen23 am 29 Mai 2020
Use conv2 to calculate the averages, e.g.:
out = matrix2.*conv2(matrix1,ones(3,3),'same')/9;
  2 Kommentare
Ahmed Abdulla
Ahmed Abdulla am 29 Mai 2020
this is works great thank youu!
Only one problem, if the 1 was in the first column then the average is disrupted because there are no cells to the left but we are still dividing by 9. how can i do the same but divide by 6 and only considering the 1's in the first column of the matrix
Stephen23
Stephen23 am 29 Mai 2020
Instead of dividing by 9 you could divide by a matrix of the same size, where each element's value gives the number that you want to divide by. Also note that the corners have 4, the sides 6, and the middle 9:
D = ones(size(matrix1))*6;
D(2:end-1,2:end-1) = 9;
D([1,end],[1,end]) = 4;
out = matrix2.*conv2(matrix1,ones(3,3),'same')./D;
Or if you have the image toolbox you could just use blockproc:

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Resizing and Reshaping Matrices finden Sie in Help Center und File Exchange

Tags

Produkte


Version

R2019b

Community Treasure Hunt

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

Start Hunting!

Translated by