Find blocks iof non-zero values in Matrix
5 views (last 30 days)
Show older comments
Hi,
I have a matrix m=(120x240) of values and randomly distributed zeros.
I would like to find all contiguous blocks of size 20x6 without any zeros. And if possible the min. value inside the block should be above predifined threshold (thr=13).
Is this possible without a loop, because I need to "search" many matrices.
Thank you
0 Comments
Answers (2)
John D'Errico
on 14 Apr 2025
Sure. It should even be pretty easy.
A = randi(200,[120,240]); % make up a matrix
First, I'll convert it to binary, where a 1 corresponds to a non-zero value greater than 13.
thresh = 13;
Abin = A > thresh;
That works, since zero is less than 13 anyway. Now just use conv2, with a 20x6 array for the convolution kernel, and the valid flag. find will do the job then.
Aconv = conv2(Abin,ones(20,6),'valid');
[r,c] = find(Aconv == 20*6)
r and c will be the locations of the upper left corner of each located block in the original array. In this case, there were two blocks found, ech slightly larger than the 20x6 requirement.
3 Comments
Matt J
on 14 Apr 2025
Edited: Matt J
on 15 Apr 2025
my goal is to have at the end a cell containing the blocks, assuming there are 2 blocks in the matrix
That will be very inefficient. Note that with a 20x6 sliding window, the existence of one block with a minimum at the threshold means there are potentially 120 nearby blocks containing the same minimum. So you will end up duplicating a lot of data. Also, there is no way in Matlab to iterate through a cell array with anything faster than a for-loop, so if speed is the goal, cell arrays are a bad choice for the container.
See Also
Categories
Find more on Loops and Conditional Statements 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!