Hi, is it possible to count the number of ones in a matrix ?

395 visualizzazioni (ultimi 30 giorni)
Example: Suppose we a have a matrix A=[1 0 0 1 0 0; 1 0 0 0 1 1]; how do I count the number of ones in this matrix??

Risposta accettata

Ahmet Cecen
Ahmet Cecen il 8 Apr 2016
Modificato: Ahmet Cecen il 8 Apr 2016
sum(A(:) == 1);
  6 Commenti
Walter Roberson
Walter Roberson il 21 Giu 2021
A = randi([0 1], 5, 5); A = xor(A,A.'); %random symmetric
A
A = 5×5 logical array
0 0 0 1 1 0 0 0 0 1 0 0 0 0 1 1 0 0 0 0 1 1 1 0 0
[r,c] = find(A);
mask = r>=c;
r = r(mask); c = c(mask);
[r,c]
ans = 4×2
4 1 5 1 5 2 5 3
or
[r,c] = find(tril(A))
r = 4×1
4 5 5 5
c = 4×1
1 1 2 3

Accedi per commentare.

Più risposte (0)

Categorie

Scopri di più su Matrices and Arrays in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by