count the number of ones in each row

1 次查看(过去 30 天)
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

回答(1 个)

KSSV
KSSV 2022-6-6
编辑:KSSV 2022-6-6
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

类别

Help CenterFile Exchange 中查找有关 Logical 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by