Need help vertically/horizontally scanning a binary matrix with reference to an indexed point!
Show older comments
So I have a binary matrix (just zeros and ones) with dimensions 400 by 500. I want to perform vertical and horizontal scans (that simply count how many zeros are to the left, right, top, bottom) through the matrix centered at a specific point.
Let's call my Matrix BW. I have an index such that BW(i,j). To find how many units are to the left, right, top, bottom I calculate these variables:
tothetop=i-1;
tothebottom=400-tothetop;
totheleft=j-1;
totheright=500-totheleft;
I tried to do a scan up and down from the point (i,j) with the following loops where TopCount & BotCount keep track of how many 0's are detected above and below the point at i,j:
for p=1:1:tothetop
if BW(p,j)==0
TopCount=TopCount+1;
end
end
for q=tothebottom:1:rows
if BW(q,j)==0
BotCount=BotCount+1;
end
end
However, I find that my counts are not accurate, namely, my scan downwards looks very similar to my scan upwards. If there is something wrong, I can't seem to figure it out, so please help!
5 Comments
I wrote a few lines which I believe could help you solve your problem. It creates a random 5 by 5 matrix with zeros and ones. I defined the center point as point P(3,3). It uses the position of the center point to look for the zeros you require.
tmp = randi([0 1],5,5);
xcenter = 3;
ycenter = 3;
left = numel(find(~(tmp(:,1:(xcenter-1)))));
up = numel(find(~(tmp(1:(xcenter-1),ycenter))));
down = numel(find(~(tmp((xcenter+1):end,ycenter))));
right = numel(find(~(tmp(:,((ycenter+1:end))))));
tmp = [1 0 1 0 1
1 0 1 0 1
1 0 1 0 0
0 1 1 1 1
1 1 1 1 1]
Left = 4. Up = 0. Down = 0. Right = 4.
To confirm, is this the output you require?
Guillaume
on 30 May 2018
@Paolo,
a faster and simpler way of obtaining
numel(find(~x))
is
sum(~x)
Aydin Akyol
on 30 May 2018
Aydin Akyol
on 30 May 2018
Guillaume
on 31 May 2018
Actually, even simpler than sum, is nnz.
Answers (0)
Categories
Find more on Matrix Indexing 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!