【问题标题】:Maximum sum all prime submatrix所有素子矩阵的最大和
【发布时间】:2017-04-01 18:58:47
【问题描述】:

问题在标题中给出。我解决这个问题的方法是这样的:

  1. 创建一个二进制矩阵 B,其中 1s 表示输入中的素数,比如说 V,它是 nxn 非负整数矩阵
  2. 找出所有正子矩阵,包括 1x1 来自 B 的子矩阵
  3. 求它们的总和,返回最大的那个,子矩阵的左上角和它的大小。

从这个意义上说,我的算法的第 2 部分似乎有点复杂。有没有办法在没有蛮力的情况下找到它们,我认为,通过 for 循环迭代并找到它们。我希望 matlab 有一个返回我想要的函数。

感谢任何帮助。

【问题讨论】:

  • 你想要所有的矩形子矩阵,还是严格的方形子矩阵?您是在计算这些子矩阵中素数的数量,还是将这些素数的值相加?

标签: matlab primes submatrix


【解决方案1】:

这与您的计划大致相同:

% generate random matrix
sz = [20 20];
imax = 200;
A = randi(imax,sz);
% binary matrix of primes
B = isprime(A);
% concat both
C = cat(3,A,B);
% compute maximum number of rows&cols in each cc in B
cc = bwconncomp(B,4);
[rows,cols] = cellfun(@(ind)ind2sub(size(B),ind),cc.PixelIdxList,'UniformOutput',false);
maxwidth = max(cellfun(@(c) max(c) - min(c),cols)) + 1;
maxheight = max(cellfun(@(c) max(c) - min(c),rows)) + 1;
% find max-sum sub matrix
valMax = 0;
idxMax = [0,0];
for ii = 1:maxheight
    for jj = 1:maxwidth
        % generate rectangle filter
        h = ones(ii,jj);
        n1 = ii*jj; % number of elements in filter
        % filter the concat matrix
        res = imfilter(C,h);
        % indexes of cc having rectangular shape
        idxs = find(res(:,:,2) == n1);
        if isempty(idxs)
            break
        end
        % find max value of all relevant rectangles 
        [v,i] = max(res(idxs));
        if v > valMax
            valMax = v; % max value
            [r,c] = ind2sub(size(B),idxs(i));
            r = r - ceil(ii/2) + 1;
            c = c - ceil(jj/2) + 1;
            idxMax = [c,r,jj,ii]; % max value rect [x,y,w,h]
        end
    end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    • 2020-06-05
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 2011-02-08
    相关资源
    最近更新 更多