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

23 ビュー (過去 30 日間)
Ines
Ines 2012 年 5 月 3 日
編集済み: Souarv De 2023 年 5 月 23 日
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
Muhammad Ilias Amin 2014 年 5 月 12 日
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 Center および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by