Find blocks iof non-zero values in Matrix

4 Ansichten (letzte 30 Tage)
CSCh
CSCh am 14 Apr. 2025
Bearbeitet: Matt J am 15 Apr. 2025
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

Antworten (2)

Matt J
Matt J am 14 Apr. 2025
Bearbeitet: Matt J am 14 Apr. 2025
Yes, the locations of the blocks are given by,
f=@(z,k,dim) movmin(z,k,dim,Endpoints='fill');
locations = f( f( m ,6,2) ,20,1) > threshold ;

John D'Errico
John D'Errico am 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 = 7×1
2 3 2 3 54 55 56
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
c = 7×1
96 96 97 97 214 214 214
<mw-icon class=""></mw-icon>
<mw-icon class=""></mw-icon>
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 Kommentare
Matt J
Matt J am 14 Apr. 2025
Bearbeitet: Matt J am 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.
CSCh
CSCh am 14 Apr. 2025
What would be a better choice for a container? A Table? My version contains a while loop, that was very slow. Both method would be very nice to have, blocks how are totally seperated and a version where a sliding window would be allowed.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte


Version

R2024a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by