How to compare a matrix element with its neighbours without using a loop in MATLAB?

前端 未结 3 1676
天涯浪人
天涯浪人 2021-02-20 09:06

I have a matrix in MATLAB. I want to check the 4-connected neighbours (left, right, top, bottom) for every element. If the current element is less than any of the neighbours the

3条回答
  •  天命终不由人
    2021-02-20 09:21

    If you have the image processing toolbox, you can do this with a morpological dilation to find local maxima and suppress all other elements.

    array = magic(6); %# make some data
    
    msk = [0 1 0;1 0 1;0 1 0]; %# make a 4-neighbour mask
    
    %# dilation will replace the center pixel with the 
    %# maximum of its neighbors
    maxNeighbour = imdilate(array,msk);
    
    %# set pix to zero if less than neighbors
    array(array

    edited to use the same data as @gnovice, and to fix the code

提交回复
热议问题