Effacer les filtres
Effacer les filtres

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

20 vues (au cours des 30 derniers jours)
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

Réponse acceptée

Image Analyst
Image Analyst le 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.

Plus de réponses (1)

Amit
Amit le 26 Jan 2014
Modifié(e) : Amit le 26 Jan 2014
tmp = A';
B = tmp(tmp > 0);

Catégories

En savoir plus sur Matrix Indexing dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by