count rectangles on big matrices
Show older comments
Hello. I have very large sparse matrices with zero and one only and i have to count all the rectangles that there are in it. For example:
1 0 0 0 1
H=[1 1 0 1 1]
0 1 1 1 0
0 0 0 0 1
There are 2 rectangles inside.
1st--> H(1,1),H(2,1),H(1,5),H(2,5)
2nd--> H(2,2),H(3,2),H(2,4),H(3,4)
I wrote a code but it is very slow with large matrices..
for i=1:m
for j=1:n
if H(i,j)==1
for ii=i+1:m
if H(ii,j)==1
for jj=j+1:n
if H(i,jj)==1
if H(ii,jj)==1
cycles=cycles+1;
end
end
end
end
end
end
end
end
Any ideas please?
10 Comments
Azzi Abdelmalek
on 27 Sep 2013
What is the size of your matrix?
One think you can do that may/may not help much depending on the data structure -- you can abort the loop on any row column that has
sum(i,:) < 2
for rows or
sum(:,j) <2
for columns as there can be no second corner on that row/column
ADDENDUM:
Also if you keep track of where the first/last are you can run the loops over only the actual range instead of entire row/column dimension
Image Analyst
on 28 Sep 2013
Can you explain why you need this?
And what about the following situations:
0 0 1 0 0
1 0 1 0 1 Is it 1 or 2 ?
1 1 1 1 1
0 0 1 0 0
0 0 1 0 0
1 0 1 0 1 Is it 1 or 0 (because cut) ?
1 1 0 1 1
0 0 1 0 0
1 1 1 1 1
1 0 0 0 1 Is it 1,2,4 ?
1 0 0 0 1
1 1 1 1 1
freebil
on 28 Sep 2013
Cedric
on 28 Sep 2013
Ok, I am starting to understand, but could you explain how you counted 15? Depending the logic that I follow accounting for various shapes, I count 9 or 33 but not 15.. ?
freebil
on 28 Sep 2013
Cedric
on 28 Sep 2013
Please, see the edit in my answer.
Accepted Answer
More Answers (1)
Image Analyst
on 28 Sep 2013
Rather than spend time looping over all the indices, many of which don't have 1's and are thus a waste of time, why not just get the rows and columns where the 1's live and then just loop over them?
[rows, columns] = find(H);
numberOfPoints = length(rows);
for k1 = 1 : numberOfPoints
row1 = rows(k1);
col1 = columns(k1);
for k2 = k1+1 : numberOfPoints
row2 = rows(k2);
col2 = columns(k2);
for k3 = k2+1 : numberOfPoints
row3 = rows(k3);
col3 = columns(k3);
for k4 = k3+1 : numberOfPoints
row4 = rows(k4);
col4 = columns(k4);
etc.
or something like that...
Categories
Find more on Time Series Objects in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!