MATLAB: How to find the non-zero column in a matrix and create it as a single matrix

find and create

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

Best Answer

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.