问题#1
我能想到的最像 Matlab 的方法是二维卷积(conv2 https://www.mathworks.com/help/matlab/ref/conv2.html)(正如我现在看到的@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 https://www.mathworks.com/help/matlab/ref/movsum.html函数,两次(每个维度一次):
result = movsum(movsum(M, N, 1, 'Endpoints', 'discard'), N, 2, 'Endpoints', 'discard');
Example:
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
否则,检查卷积不为零的地方:
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