locmax.m

来自「求极值的程序」· M 代码 · 共 91 行

M
91
字号
function [result] = locmax(input, len)
[x,y] = size(input);
theend = floor(x / len) * len;
result = zeros(x, y);
step = floor(len / 2);

% looking for the local max in the matrix
for i = 1:1:theend
    lmax = input(i);
    lpmax = i;
    for j = -step:1:step
        if (i+j > 0) & (i+j < theend)
            if(input(i + j) > lmax)
                lmax = input(i + j);
                lpmax = i+j;
            end
        end
    end
%    result((i- 1)/len + 1,1) = lpmax;
%    result((i- 1)/len + 1,2) = lmax;
    
    if (lmax > 0 )
        result(lpmax,1) = lpmax;
        result(lpmax,2) = lmax;
    end 
    % when get the max, set the max position 0. then to find the second max
    input(lpmax) = 0;
    lmax2 = input(i);
    lpmax2 = i;
    for j = -step:1:step
        if (i+j > 0) & (i+j < theend)
            if(input(i + j) > lmax2)
                lmax2 = input(i + j);
                lpmax2 = i+j;
            end
        end 
    end
%    result((i- 1)/len + 1,3) = lpmax2;
%    result((i- 1)/len + 1,4) = lmax2;
 
    if lmax2 > 0
        result(lpmax2,3) = lpmax2;
        result(lpmax2,4) = lmax2;
    end
    % recovery the max with max value
    input(lpmax) = lmax;
end
if x > theend
    lmax = input(theend + 1);
    lpmax = theend + 1;
    for j = -step:1:step
        if (j < x)
            if(input(j) > lmax)
                lmax = input(j);
                lpmax = j;
            end
        end 
    end
%    result(theend/len + 1,1) = lpmax;
%    result(theend/len + 1,2) = lmax;
    
    if (lmax > 0)
        result(lpmax,1) = lpmax;
        result(lpmax,2) = lmax;
    end
    % when get the max, set the max position 0. then to find the second max
    input(lpmax) = 0;
    lmax2 = input(theend + 1);
    lpmax2 = theend + 1;
    for j = -step:1:step
        if (j < x)
            if(input(j) > lmax2)
                lmax2 = input(j);
                lpmax2 = j;
            end
        end
    end
%    result((i- 1)/len + 1,3) = lpmax2;
%    result((i- 1)/len + 1,4) = lmax2;
    
    if (lmax2 > 0)
        result(lpmax2,3) = lpmax2;
        result(lpmax2,4) = lmax2;
    end 
    
    % recovery the max with max value
    input(lpmax) = lmax;
end


⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?