How can I change an element in a matrix with the median of itself and its surrounding elements.

2 ビュー (過去 30 日間)
Let's say I have a 10x10 matrix. For the element in the second row and second column, I want the median of the 3x3 matrix that surrounds that element, and I want the number replaced by the median. I also want this process to continue across the matrix rows and down the columns. I have the nested for loops set up to do have the calculations move in the direction they need to move, but I do not know how to specify the median function to take the localized 3x3 matrix of a larger array.

回答 (2 件)

Walter Roberson
Walter Roberson 2021 年 3 月 9 日
編集済み: Walter Roberson 2021 年 3 月 9 日
medfilt2() is already part of the Image Processing Toolbox.
You can also implement in terms of nlfilter() https://www.mathworks.com/help/images/ref/nlfilter.html which is also part of the toolbox.
If you need to code it yourself, then just use nested for loops and extract M(row-1:row+1, col-1:col+1) and take the median of that.

per isakson
per isakson 2021 年 3 月 9 日
編集済み: per isakson 2021 年 3 月 9 日
"but I do not know how to specify the median function to take the localized 3x3 matrix of a larger array"
Combine these two examples. Calculate the median of a matrix
>> m3x3 = reshape( randperm(9), 3,3 ) % sample data
m3x3 =
7 5 4
2 6 1
8 9 3
>> median( m3x3(:) )
ans =
5
and find submatrix
>> m10x10 = reshape( (1:100), 10,10 ); % sample data
>> r = 7; c = 3; % sample data, row and column
>> m3x3 = m10x10( r-1:r+1, c-1:c+1 )
m3x3 =
16 26 36
17 27 37
18 28 38

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by