【问题标题】:MATLAB change elements to zero based on surrounding dataMATLAB 根据周围数据将元素更改为零
【发布时间】:2015-02-10 00:31:53
【问题描述】:

只是一个矩阵问题,可能很简单,我无法弄清楚。假设我有一个 20 x 20 的矩阵 A。我有另一个大小相同但合乎逻辑的矩阵 B。我希望 A 中位置在 B 中“1”的(例如)3 内的任何元素都更改为 0。

詹姆斯

【问题讨论】:

  • 如何测量矩阵元素之间的距离?

标签: matlab matrix nearest-neighbor


【解决方案1】:

图像处理工具箱包含一个函数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;

【讨论】:

    【解决方案2】:

    代码

    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;
    

    调试输入和输出 -

    【讨论】:

    • Matlab 总是因其工具箱而备受赞誉,而事实上您只需要bsxfun。 :-)
    • @knedlsepp 这正是我告诉别人的!实际上对于这个问题conv2 可能是最有效的一个,因为即使有这个bsxfun,也有多个覆盖!
    • 哦对了,刚刚测试过了。高达 N=500 conv2 击败 imdilate。根据您到目前为止的所有答案,您可以将图像处理工具箱的免费版本与相当的速度结合起来。 :-)
    • @knedlsepp 是的,我是这么认为的! imdilate 有时会很慢。
    猜你喜欢
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 2014-04-05
    相关资源
    最近更新 更多