function to count number of '1' in each row and column
4 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Firas Al-Kharabsheh
am 29 Mär. 2016
Bearbeitet: Image Analyst
am 29 Mär. 2016
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
2 Kommentare
Matthew Eicholtz
am 29 Mär. 2016
Bearbeitet: Matthew Eicholtz
am 29 Mär. 2016
I do not understand how Matrix_row and Matrix_col are being computed. Currently, it is not the number of ones in the each row or column (as far as I can tell). Can you provide more details?
Image Analyst
am 29 Mär. 2016
Bearbeitet: Image Analyst
am 29 Mär. 2016
Matt, it's basically the lengths of the "runs" of 1's in each direction, then padded with zeros to make it rectangular. Though I'm not sure why Matrix_col has a top row of all zeros - seems like that should have been omitted. So the first row has groupings/runs of 1's of lengths 3, 1, and then 2, each separated by zeros. The last row has 4 separate runs, so the Matrix_row array needs to have (at least) 4 columns. If some row had only , say, 2 runs, you'd have to append two zeros to make that row have the full 4 columns.
By the way, the lengths of the runs can be determined from regionprops() very, very easily:
stats = regionprops(logical(oneRow), 'Area');
allLengths = [stats.Area]; % Would give 3,1,2 for the first row in the example matrix.
By the way, this is a duplicate to http://www.mathworks.com/matlabcentral/answers/275707#answer_215257 where I outlined the solution but didn't give a complete solution because it seemed to be his assignment.
Akzeptierte Antwort
Azzi Abdelmalek
am 29 Mär. 2016
Bearbeitet: Azzi Abdelmalek
am 29 Mär. 2016
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))
2 Kommentare
Weitere Antworten (0)
Siehe auch
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!