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.
0 个评论
回答(2 个)
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.
0 个评论
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!