-1

The problem is given in the title. My approach to this problem is like that:

  1. Create a binary matrix B where 1s represents the prime numbers in the input let say V, which is nxn non negative integer matrix
  2. Find all the positive submatrices including 1x1 fom B
  3. Find the sum of them and return the greatest one with the left top corner of the submatrix and the size of it.

In this sense, section 2 of my algorithm seems a little complicated. Is there any way to find them without the brute force, which is I think, iterating via for loops and finding them. I am hoping that matlab has a function returning what I want.

Any help is appreciated.

Sami
  • 490
  • 6
  • 29
  • Do you want all rectangular submatrices, or strictly square submatrices? Are you counting the number of primes within these submatrices, or summing the values of those primes? – beaker Apr 02 '17 at 17:45

1 Answers1

1

this is approximately what you planned:

% 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
user2999345
  • 4,195
  • 1
  • 13
  • 20