问题在标题中给出。我解决这个问题的方法是:
从这个意义上讲,我算法的第2部分看起来有点复杂。有没有办法在没有蛮力的情况下找到它们,我认为这是通过for循环迭代并找到它们。我希望matlab有一个函数返回我想要的东西。
感谢任何帮助。
答案 0 :(得分: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