How do I find the non-zero column in a matrix and create it as a single matrix?

22 ビュー (過去 30 日間)
Amar
Amar 2014 年 1 月 26 日
回答済み: Image Analyst 2014 年 1 月 26 日
i.e from A =
[0 0 0 0 0 0 2 0 0]
0 0 0 0 0 0 5 0 0
create B=
[2]
5

採用された回答

Image Analyst
Image Analyst 2014 年 1 月 26 日
Try this:
% Create sample data where column 3 and 7 are not completely zeros.
A =[0 0 0 0 0 0 2 0 0;
0 0 0 3 0 0 5 0 0]
% Determine which columns have 0 in every row.
columnsWithAllZeros = all(A == 0)
% The code above will show columns 1,2,3,5,6,8, & 9 are all zeros.
% Other columns(4 & 7) must have at least one non-zero element
% so keep only those columns, not the all-zero columns.
B = A(:, ~columnsWithAllZeros)
Note that this code is robust in that it will keep all columns that have at least one non-zero element in them. The columns you keep can have a zero in them and still be kept. Amit's answer does not do that and does not give a 2D array. Pick whichever one does what you want. His answer will give you exactly what you asked for, for the specific case you gave. It just depends on how general/flexible and robust you want to be.

その他の回答 (1 件)

Amit
Amit 2014 年 1 月 26 日
編集済み: Amit 2014 年 1 月 26 日
tmp = A';
B = tmp(tmp > 0);

カテゴリ

Help Center および File ExchangeElementary Math についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by