Count the number of non-zero elements of a column/row of a 2D-Matrix?

80 vues (au cours des 30 derniers jours)
Ines
Ines le 3 Mai 2012
Modifié(e) : Souarv De le 23 Mai 2023
Hello everyone,
I have a 2D Matrix and I want to make Matlab count the number of non-zero Elements within one row, is there a straightforward way to do this? Many thanks

Réponse acceptée

James Tursa
James Tursa le 3 Mai 2012
sum(X(row_number,:)~=0)

Plus de réponses (2)

Thomas
Thomas le 3 Mai 2012
Try:
a=[3 0 0;0 2 0; 1 0 4] %input matrix
sum(a~=0,2) % no. of nozero elements in each row

Muhammad Ilias Amin
Muhammad Ilias Amin le 12 Mai 2014
a = [3 0 0; 0 2 0; 1 0 0];
To get the no of non zero columns: sum( all( a == 0, 1 ) );
To get the no of non zero rows: sum( all( a == 0, 2 ) );
  1 commentaire
Souarv De
Souarv De le 23 Mai 2023
Modifié(e) : Souarv De le 23 Mai 2023
A small correction in the text part to the above two lines code is that it will give no of zero columns and rows, not non-zero columns and non-zero rows.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by