【发布时间】:2015-02-10 00:31:53
【问题描述】:
只是一个矩阵问题,可能很简单,我无法弄清楚。假设我有一个 20 x 20 的矩阵 A。我有另一个大小相同但合乎逻辑的矩阵 B。我希望 A 中位置在 B 中“1”的(例如)3 内的任何元素都更改为 0。
詹姆斯
【问题讨论】:
-
如何测量矩阵元素之间的距离?
标签: matlab matrix nearest-neighbor
只是一个矩阵问题,可能很简单,我无法弄清楚。假设我有一个 20 x 20 的矩阵 A。我有另一个大小相同但合乎逻辑的矩阵 B。我希望 A 中位置在 B 中“1”的(例如)3 内的任何元素都更改为 0。
詹姆斯
【问题讨论】:
标签: matlab matrix nearest-neighbor
图像处理工具箱包含一个函数imdilate,可以将B靠近1s的位置填入1s。然后我们只对A 使用逻辑索引。您提到的距离是使用欧几里得距离计算的。如果您想要棋盘距离,请改用neighborhood = ones(2*R+1)。
R = 3;
[X,Y] = ndgrid(-ceil(R):ceil(R));
neighborhood = (X.^2 + Y.^2)<=R^2;
A(imdilate(B,neighborhood)) = 0;
【讨论】:
代码
bsxfun 解决此类问题的方法 -
%// Form random A and B for demo purposes
N = 50; %// input datasize
A = rand(N);
B = rand(N)>0.9;
R = 2; %// neighbourhood radius
%// Find linear indices offsets within 2R*2R neighbourhood
offset_displacement = bsxfun(@plus,(-R:R)',[-R:R]*size(A,1)); %//'
offset_matches = bsxfun(@plus,(-R:R)'.^2,[-R:R].^2) <= R*R; %//'
offset_matched_displacement = offset_displacement(offset_matches);
%// Use those offsets to find actual linear indices for all '1' points in B
loc = bsxfun(@plus,find(B),offset_matched_displacement'); %//'
%// Set "eligible" points (based on loc) to zeros in A
A(loc(loc>=1 & loc<=numel(A)))=0;
调试输入和输出 -
【讨论】:
bsxfun。 :-)
conv2 可能是最有效的一个,因为即使有这个bsxfun,也有多个覆盖!
conv2 击败 imdilate。根据您到目前为止的所有答案,您可以将图像处理工具箱的免费版本与相当的速度结合起来。 :-)
imdilate 有时会很慢。