矩阵的滑动窗口求和 [英] Sliding window summation of a matrix
问题描述
我有一个50x50的矩阵,我想对每10x10(或另一个设置大小的值-始终为正方形)重叠网格中的值求和,即:
I have a 50x50 matrix, and I'd like to sum up the values in every 10x10 (or another set size value - always square) overlapping grid i.e.:
为清楚起见,重叠窗口仅以对角线显示.我尝试做的第一个任务是定义每个窗口的坐标:
Overlapping windows are shown only in the diagonal for the sake of clarity. The first task I've tried to do is define the coordinates of each window:
win=10;
start = [1,10,1,10];
for y=1:(50-win)
for g=1:(50-win)
tmp = [start(g,1)+1,start(g,2)+1,start(end,3),start(end,4)];
start = [start;tmp];
end
start(end+1,1:4) = [1,10,1+y,10+y];
end
然后我将对每个窗口使用sum
和逻辑索引遍历坐标列表.
And then I'd loop over the list of coordinates, using sum
and logical indexing for each window.
问题1 :上面的代码并不是特别雄辩.任何人都可以展示出更"MATLABesque"的方式或更简洁的方式吗?
PROBLEM #1: The above code is not particularly eloquent. Can anybody show a more 'MATLABesque' way of doing it or a more concise way?
问题2 :然后,我想在矩阵中定义特定的坐标(索引),例如m(26,26)
并获取此坐标包含在其中的所有窗口的列表.但是我不知道该怎么做.有人可以告诉我怎么做吗?
PROBLEM #2: I'd then like to define a particular coordinate (index) in the matrix e.g. m(26,26)
and get a list of all windows this coordinate is contained within. But I have no idea how to do this. Can anybody show me how?
推荐答案
问题1
Problem #1
The most Matlab-like way for doing this I can think of is two-dimensional convolution (conv2
) (as I now see was commented by @rahnema1):
M = randi(9, 5, 5); % input: square matrix, arbitrary size
N = 3; % block size, assumed square, not larger than M
result = conv2(M, ones(N), 'valid');
等效地,您可以使用最近引入的 movsum
函数,两次(每个维度一次):
Equivalently, you can use the recently introduced movsum
function, twice (once for each dimension):
result = movsum(movsum(M, N, 1, 'Endpoints', 'discard'), N, 2, 'Endpoints', 'discard');
示例:
M =
4 4 3 1 2
2 8 7 1 6
3 6 7 5 5
6 5 4 8 1
5 9 6 9 4
result =
44 42 37
48 51 44
51 59 49
问题2
最简单的方法(不是最有效的方法)是再次使用卷积,将逻辑矩阵包含在所需位置的true
,否则包含false
,并检查卷积不为零的地方:
Problem #2
The simplest way (not the most efficient one) is to use convolution again with a logical matrix containing true
at the desired position and false
otherwise, and checking where the convolution is not zero:
in_coords = [3 4]; % example input coordinates
T = false(size(M)); % initiallize matrix containing false, same size as M
T(in_coords(1), in_coords(2)) = true; % true at the desired coordinates
C = conv2(T, ones(N), 'valid'); % this gives 1 for blocks affected by in_coords
[ii, jj] = find(C); % row and column indices of nonzero values
out_coords = [ii jj]; % build result
在此示例中,
out_coords =
1 2
2 2
3 2
1 3
2 3
3 3
这篇关于矩阵的滑动窗口求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!