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

23 次查看(过去 30 天)
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 CenterFile Exchange 中查找有关 Elementary Math 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by