Find blocks iof non-zero values in Matrix

조회 수: 2 (최근 30일)
CSCh
CSCh 2025년 4월 14일
편집: Matt J 2025년 4월 15일
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

답변 (2개)

Matt J
Matt J 2025년 4월 14일
편집: Matt J 2025년 4월 14일
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 2025년 4월 14일
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
Matt J
Matt J 2025년 4월 14일
편집: Matt J 2025년 4월 15일
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 2025년 4월 14일
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.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2024a

Community Treasure Hunt

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

Start Hunting!

Translated by