count the number of ones in each row

3 views (last 30 days)
kurdistan mohsin
kurdistan mohsin on 6 Jun 2022
Edited: KSSV on 6 Jun 2022
hi, i have the below N by N matrix and i want to count the number of ones in each row , anyone can help ?
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 1 1
0 0 0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 1 0 0 0 0 0 1 1
0 0 1 0 0 0 0 1 0 0
0 0 1 0 0 0 0 1 0 0

Answers (1)

KSSV
KSSV on 6 Jun 2022
Edited: KSSV on 6 Jun 2022
A = [0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 1 1 1
0 0 0 0 1 0 0 0 0 0
0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 0 1 0 0 0
0 0 0 0 0 1 0 0 0 0
0 0 1 0 0 0 0 0 1 1
0 0 1 0 0 0 0 1 0 0
0 0 1 0 0 0 0 1 0 0] ;
[m,n] = size(A) ;
C = zeros(m,1) ;
for i = 1:m
C(i) = nnz(A(i,:)) ;
end
C
C = 10×1
0 0 3 1 1 1 1 3 2 2
Or Simply:
C = sum(A==1,2)
C = 10×1
0 0 3 1 1 1 1 3 2 2

Categories

Find more on Operating on Diagonal Matrices 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!