Function to find number of 1 in binary Matrix for each row and for each coulmn
3 views (last 30 days)
Show older comments
if i have a (M x N) binary matrix where M is number of row and N is number of Column like this example below
MatrixA = [ 0 0 1 1 1 1 0 1 1
1 1 0 1 0 1 1 0 1
1 0 1 1 1 0 1 0 0
0 1 1 0 1 1 0 1 1
1 1 0 1 0 1 1 1 0
0 0 1 1 1 0 0 0 1 ]
so i want to calculate the number in each row in condition if the number 1 appear in sequence for example (1 0 1 1 1) then the output will be (1 3) and put the result in new (M x N/2) matrixR like this solution
MatrixR = [0 0 0 4 2
0 2 1 2 1
0 0 1 3 1
0 0 2 2 2
0 0 2 1 3
0 0 0 3 1 ]
and the function will be able to do this for the a third (M/2 x N) MatrixC for the Column like this solution
MatrixC = [ 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 1 0 1 0 0 0 2
2 1 2 3 2 2 2 1 1
1 2 1 2 1 2 1 2 1 ]
1 Comment
Image Analyst
on 29 Mar 2016
He didn't use my answer and asked again in http://www.mathworks.com/matlabcentral/answers/275985-function-to-count-number-of-1-in-each-row-and-column, which is basically a duplicate of this one.
Answers (2)
Image Analyst
on 27 Mar 2016
If this homework?
Scan the array row-by-row, or column-by-column, and call bwlabel() and then regionprops(binaryLine, 'Area')
That gives you an array with the length of all the 1 runs.
for row = 1 : rows
thisLine = M(row, :);
..... = bwlabel(......
stats = regionprops(........
allAreas = [stats.Area];
M2(........
end
That's a start. You finish it.
2 Comments
Walter Roberson
on 27 Mar 2016
The question looks familiar. I believe we had someone else ask it about 5 months ago.
Andrei Bobrov
on 29 Mar 2016
Edited: Andrei Bobrov
on 29 Mar 2016
for columns
A = MatrixA;
a1 = cumsum([A(1,:);diff(A)==1]).*A+1;
[m,n] = size(a1);
q = accumarray([a1(:),kron((1:n)',ones(m,1))],1,[m-1,n]);
q(1,:) = 0;
MatrixC = zeros(m-1,n);
t = q > 0;
MatrixC(sort(t)) = q(t);
for rows
a0 = [A(:,1), diff(A,1,2)==1];
a1 = cumsum(a0,2).*A+1;
q = accumarray([kron(ones(n,1),(1:m)'),a1(:)],1,[m,n-4])';
q(1,:) = 0;
t = q > 0;
z = zeros(size(q));
z(sort(t)) = q(t);
MatrixR = z';
0 Comments
See Also
Categories
Find more on Number Theory in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!