我有一个220 * 366的矩阵,我想设置一个3 * 3的窗口来选择矩阵中的元素。 例如:
matrix = [1, 2, 3, 4, 5;
6, 7, 8, 9, 10;
11,12,13,14,15];
window = [1, 2, 3;
6, 7, 8;
11,12,13];
答案 0 :(得分:0)
如果您拥有图像处理工具箱,则可以使用nlfilter
:
function out = q52158450()
% Create a matrix:
Rm = 220; Cm = 366;
matrix = randn(Rm,Cm);
% Define the window and apply filter:
Rw = 6; Rc = 6;
windows = nlfilter(matrix, [Rw, Rc], @getwindow);
% Select subset of outputs, removing zero-padded boundary elements:
Bw = floor((Rw-1)/2); Bc = floor((Rc-1)/2);
out = windows(Bw:end-Bw, Bc:end-Bc); % < Output is a cell
function out = getwindow(in)
out = {in};
否则,可以通过双循环来完成:
function out = q52158450()
% Create a matrix:
Rm = 220; Cm = 366;
matrix = randn(Rm,Cm);
% Define the window and apply filter:
Wr = 3; Wc = 3;
Br = ceil(Wr/2); Bc = ceil(Wc/2);
out = cell(Rm-Br, Cm-Bc);
for indR = 1:Rm-Wr+1
for indC = 1:Cm-Wc+1
out{indR, indC} = matrix(indR:indR + Wr - 1, indC:indC + Wc - 1);
end
end