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

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

采纳的回答

James Tursa
James Tursa 2012-5-3
sum(X(row_number,:)~=0)

更多回答(2 个)

Thomas
Thomas 2012-5-3
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
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 个评论
Souarv De
Souarv De 2023-5-23
编辑:Souarv De 2023-5-23
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by