Find the column with the least number of 1s (ones) in it | Find column with at least one non zero element

2 visualizaciones (últimos 30 días)
Consider I have a m by n matrix with binary data
Is there a easy way to write a code that can identify the column with the least number of ones in them.
My current code identifies the column with zero 1s, which is not what I seek
H = [0 0 1 1 0 1 0 1 0 1 1 0;
0 0 0 1 0 1 1 0 1 0 1 0;
0 1 1 0 0 1 1 1 0 0 0 1;
0 1 1 0 1 0 1 0 1 0 0 0;
0 0 0 1 1 0 0 1 1 0 0 0;
0 1 0 0 1 0 0 0 0 0 1 1];
%For ex, here the column with least number of ones is column 10.
%whereas column 1 has all zero elements which is not the result I want.
%This is my code which gives wrong results
a = sum(H);
amax = max(a);
amin = min(a);

Respuesta aceptada

Walter Roberson
Walter Roberson el 23 de Dic. de 2020
count = sum(H);
idx = find(count);
[~, relidx] = min(count(idx)) ;
mincol = idx(relidx);

Más respuestas (1)

Image Analyst
Image Analyst el 23 de Dic. de 2020
If you have multiple columns where the count is the same minimum count, then you can't use min() because it will find only the FIRST occurrence. You need to use find():
H = [0 0 1 1 0 1 0 1 0 1 1 0;
0 0 0 1 0 1 1 0 1 0 1 0;
0 1 0 0 0 1 1 1 0 0 0 1;
0 1 0 0 1 0 1 0 1 0 0 0;
0 0 0 1 1 0 0 1 1 0 0 0;
0 1 0 0 1 0 0 0 0 0 1 1];
count = sum(H == 1, 1) % Can handle non-1 values also, in case they occur.
count(count==0) = nan; % Tell it to ignore a count of zero.
minCount = min(count) % Find the min count other than 0.
% Find ALL the columns where the min count can occur.
% Unfortunately, min() only finds the FIRST column.
columns = find(count == minCount) % Correctly returns both column 3 and column 10 which both have a count of 1
count =
0 3 1 3 3 3 3 3 3 1 3 2
minCount =
1
columns =
3 10

Categorías

Más información sobre Multidimensional Arrays en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by