Need help vertically/horizontally scanning a binary matrix with reference to an indexed point!

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 个评论

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?
@Paolo, I am trying to count the number of zeros to the left, right, above, and below of the defined center. Meaning that starting at the center I want to look at all elements to the left, and know how many zeroes there are. And then I want to look at all all of the elements to the right and know how many zeroes there are to the right. Given your definition of tmp and a center at (3,3), left should be 1 right should be 2, up and down should both be zero. @Guillaume sum may work. I'll look into it.
I think I'll just reverse my matrix (make all the 0's into 1 and vice versa) and then I was able to adapt the code used before to do what I wanted, with sum. So here is my scanning/summing code below:
clear
clc
close all
xcenter = 3;
ycenter = 3;
tmp = randi([0 1],5,5);
[rows,columns]=size(tmp);
left = sum(tmp((ycenter),(1:(xcenter-1))));
up = sum(tmp(1:ycenter-1,xcenter));
down = sum(tmp(ycenter+1:rows,xcenter));
right = sum(tmp((ycenter),(xcenter+1:columns)));
tmp
left
up
down
right
Thanks for the help all!

请先登录,再进行评论。

回答(0 个)

类别

帮助中心File Exchange 中查找有关 Matrix Indexing 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by