# I have to select mode from matrix with sliding window of 3X3. How to do that?

2 views (last 30 days)
Preet Lal on 15 Nov 2021
Commented: Preet Lal on 16 Nov 2021
I have to create a new matrix with mode of 3x3 sliding window, I have written code, but it's not working.
[m, n] = size(LULC_01km);
rows = ceil(m/3);
coln = ceil(n/3);
LULC_3_km = NaN(rows,coln);
for i = 2:rows-1
for j = 2:coln-1
LULC_3_km(i,j) = mode(LULC_01km((i-1:i+1), (j-1:1+j)), 'all');
end
end
Adam Danz on 15 Nov 2021
"It's not working" doesn't give us much info. What part isn't working?
• Is the moving window not sliding as expected?
• Are the outputs not stored in the expected indices?
• Do you have doubts about the output values?

Adam Danz on 15 Nov 2021
Edited: Adam Danz on 15 Nov 2021
n*m sliding mode; slides by intervals of 1
This computes the sliding mode within a 2D window that slides by 1 unit horizontally then vertically.
• LULC_01km - your n*m matrix
• winSz - define window size
• LULC_3_km - output containing modes
LULC_01km = randi(5,9,12) % n*m matrix
LULC_01km = 9×12
4 3 5 3 2 1 4 3 4 1 4 2 3 5 1 1 2 4 2 5 3 5 3 2 1 4 5 2 1 3 3 3 2 1 3 4 5 2 2 3 1 2 2 1 3 4 1 5 5 2 3 1 5 3 3 3 4 2 3 5 5 1 1 3 2 5 5 1 3 3 5 3 3 2 5 1 2 1 5 2 2 2 2 3 5 1 5 1 4 2 4 5 3 4 2 3 3 2 3 5 5 4 5 5 1 3 1 5
winSz = [3,3]; % window size [width (x), height (y)]
% Compute starting coordinate of sliding windows
[m, n] = size(LULC_01km);
winX0 = 1:n-winSz(1)+1; % starting index of x-values for each window
winY0 = 1:m-winSz(2)+1; % starting index of y-values for each window
% Loop through windows to compute mode
LULC_3_km = NaN(numel(winY0),numel(winX0));
xWin = 0:winSz(1)-1;
yWin = 0:winSz(2)-1;
for i = 1:size(LULC_3_km,1)
for j = 1:size(LULC_3_km,2)
LULC_3_km(i,j) = mode(LULC_01km(winY0(i)+yWin, winX0(j)+xWin),'all');
end
end
% Show results
LULC_3_km
LULC_3_km = 7×10
5 5 1 1 2 3 3 3 3 1 5 2 1 1 2 2 3 3 3 1 2 2 1 1 3 3 3 3 3 1 2 1 1 3 2 3 3 3 3 3 5 1 1 1 5 3 3 2 2 3 5 1 1 1 2 5 5 2 2 3 3 1 5 1 4 5 5 2 2 2
LULC_3_km(i,j) is the mode of values within the 3x3 window with the upper left corner at LULC_01km(i,j).
n*m sliding mode; slides by intervals of m (horizontally) and n (vertically)
To use a boxcar moving mode, simply redefine the winX0 and winY0 variables as
winX0 = 1:winSz(1):n-winSz(1)+1; % starting index of x-values for each window
winY0 = 1:winSz(2):m-winSz(2)+1; % starting index of y-values for each window
For a 9x12 input matrix, this will create a 3x4 ouput matrix. To see an animation of a 3x3 boxcar filter, see this answer.
Preet Lal on 16 Nov 2021
Could you please tell me how to move forward by keeping window from center, like i-1:i+1 for row 1 to 3 and next using similar condition how i can jump to 4 to 6. My code should work like this.

R2021b

### Community Treasure Hunt

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

Start Hunting!