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

83 visualizaciones (últimos 30 días)
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

Respuesta aceptada

James Tursa
James Tursa el 3 de Mayo de 2012
sum(X(row_number,:)~=0)

Más respuestas (2)

Thomas
Thomas el 3 de Mayo de 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 el 12 de Mayo de 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 comentario
Souarv De
Souarv De el 23 de Mayo de 2023
Editada: Souarv De el 23 de Mayo de 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.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by