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

23 views (last 30 days)
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

Accepted Answer

Image Analyst
Image Analyst on 26 Jan 2014
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.

More Answers (1)

Amit
Amit on 26 Jan 2014
Edited: Amit on 26 Jan 2014
tmp = A';
B = tmp(tmp > 0);

Categories

Find more on Elementary Math in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!