How can I find columns with all zeros in my matrix?

30 ビュー (過去 30 日間)
Nick Thomas
Nick Thomas 2018 年 4 月 28 日
コメント済み: Asko Köhn 2021 年 3 月 16 日
I've got a large matrix A and would like to find out if any of the columns contain only zeros. I've found a solution for finding all the rows with only zeros but I'm not sure how to make it all columns.
Also, would there be a way to find out which columns have exactly 4 or 3 or 2 or X nonzero entries?

採用された回答

Kaushik Lakshminarasimhan
Kaushik Lakshminarasimhan 2018 年 4 月 28 日
編集済み: Kaushik Lakshminarasimhan 2018 年 4 月 28 日
cols_with_all_zeros = find(all(A==0)); % all zeros
cols_with_3_nonzeros = find(sum(A~=0)==3); % exactly 3 non-zeros

その他の回答 (1 件)

Ameer Hamza
Ameer Hamza 2018 年 4 月 28 日
"I've found a solution for finding all the rows with only zeros"
If you find the solution for rows, just apply to transpose of A (i.e. A'). The rows of A' will represent corresponding columns of A. Nevertheless, the following code will give you the index of all zeros columns
columnNumbers = find(sum(abs(A)) == 0)
To find out which columns have X nonzero entries, do the following
X = 2; % columns having 2 nonzero elements
columnNumbers = find(sum(A~=0) == 4)
  1 件のコメント
Asko Köhn
Asko Köhn 2021 年 3 月 16 日
Apart from transposition of the input matrix in order to check rows instead of columns or vice versa, the same can be achieved by use of the dimension input parameter with the suggested solutions and also with any(), in which case the comparison operation with zero can be dispensed with:
col_nums = find(~any(A,1)) %default for 2D array
row_nums = find(~any(A,2))
(If A is a multidimensional array, then sum(A) operates along the first array dimension whose size does not equal 1, treating the elements as vectors. This dimension becomes 1while the sizes of all other dimensions remain the same.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeResizing and Reshaping Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by