How can I find the number of specific submatrices inside a matrix?
1 次查看(过去 30 天)
显示 更早的评论
Hi, If i ran this code,
A = randi([0, 1], [10,10])
I would get something like
A =
1 0 0 1 1 1 1 0 1 0
1 1 0 0 1 0 0 0 0 1
1 0 1 0 1 1 0 1 1 1
1 0 1 0 0 1 0 1 1 0
1 0 1 0 1 0 0 1 0 1
0 0 0 1 1 1 1 0 0 0
0 1 0 1 0 1 1 0 1 1
0 0 0 1 0 1 0 0 0 0
1 1 0 1 0 1 0 1 1 0
1 1 0 1 1 0 1 1 1 0
In this matrix i want to find how many instances the submatrix B occurs.
B = [1 1 ; 1 1]
Does anyone know of an easy way I can achieve this?
1 个评论
采纳的回答
Matt J
2022-3-13
编辑:Matt J
2022-3-14
Sa=conv2(A.^2,ones(2),'valid');
Sb=sum(B(:).^2);
n= nnz( conv2(A, rot90(B,2),'valid').^2==Sa.*Sb );
4 个评论
Image Analyst
2022-3-14
While this is correct for the given matrix of all 1's, it won't work in general for other patterns. It works by comparing the number of 1's in a sliding window over A to the number of 1's in B. It doesn't actually match the pattern. So if there are 2 or 3 in B, it would say there is a match even though the pattern is different. You want to use bwhitmiss(), which is a hit or miss transform specifically meant for this. See my answer below for the general answer that works for other patterns.
更多回答(1 个)
Image Analyst
2022-3-14
You want to use the "hit or miss transform" done by bwhitmiss(). Using conv2 will not work for arbitrary patterns. See illustrations below:
A =[...
1 0 0 1 1 1 1 0 1 0
1 1 0 0 1 0 0 0 0 1
1 0 1 0 1 1 0 1 1 1
1 0 1 0 0 1 0 1 1 0
1 0 1 0 1 0 0 1 0 1
0 0 0 1 1 1 1 0 0 0
0 1 0 1 0 1 1 0 1 1
0 0 0 1 0 1 0 0 0 0
1 1 0 1 0 1 0 1 1 0
1 1 0 1 1 0 1 1 1 0];
B = logical([0, 1; 1, 1]);
numMatchesMJ = nnz( conv2(A,B,'valid')==nnz(B) ) % 10 is incorrect
BW = bwhitmiss(A,B,~B);
BW = BW(1:end-1, 1:end-1) % 1 if upper left corner matches.
numMatches = nnz(BW) % 3 is correct.
% Another example
B = logical([1, 0; 1, 1]);
numMatchesMJ = nnz( conv2(A,B,'valid')==nnz(B) ) % 7 is incorrect
BW = bwhitmiss(A,B,~B);
BW = BW(1:end-1, 1:end-1) % 1 if upper left corner matches.
numMatches = nnz(BW) % 4 is correct.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!