MATLAB: Function to count number of ‘1’ in each row and column

binaryduplicate postfunctionmatricesmatrix

if i have a (M , N) binary matrix which M is number of rows and N is the number of column , and i want to count Number of 1 in each row and for each column , for example [1 0 1 1 0 1 1 1 1 0 1 0 ] the the output will be in new matrix like this [ 1 2 4 1]
Matrix = [ 0 1 1 1 0 0 1 0 1 1
1 0 1 1 0 1 0 1 1 0
1 1 0 0 1 1 1 1 0 1
1 1 1 1 1 0 1 0 0 1
0 0 1 0 0 1 1 1 1 0
1 1 0 1 1 0 0 1 0 1 ]
Matrix_row = [3 1 2 0
1 2 1 2
2 4 1 0
5 1 1 0
1 4 0 0
2 2 1 1 ]
Matrix_col = [0 0 0 0 0 0 0 0 0 0
0 1 0 2 0 0 0 0 0 1
3 2 2 1 1 2 1 2 2 2
1 1 2 1 1 1 3 2 1 1 ]
i need this solution because its a part of graduation project please he me

Best Answer

M = [ 0 1 1 1 0 0 1 0 1 1
1 0 1 1 0 1 0 1 1 0
1 1 0 0 1 1 1 1 0 1
1 1 1 1 1 0 1 0 0 1
0 0 1 0 0 1 1 1 1 0
1 1 0 1 1 0 0 1 0 1 ];
[n,m]=size(M);
b=cell(n,1);
c=cell(1,m);
maxb=1;
maxc=1;
for k=1:n
a=[0 M(k,:) 0];
ii1=strfind(a,[0 1]);
ii2=strfind(a,[1 0]);
maxb=max(maxb,numel(ii1));
b{k}=ii2-ii1;
end
for k=1:m
a=[0 M(:,k)' 0];
ii1=strfind(a,[0 1]);
ii2=strfind(a,[1 0]);
maxc=max(maxc,numel(ii1));
c{k}=(ii2-ii1)';
end
M_row=cell2mat(cellfun(@(x) [x zeros(1,maxb-numel(x))],b,'un',0))
M_column=cell2mat(cellfun(@(x) [zeros(1,maxc-numel(x));x],c,'un',0))