Find the column with the least number of 1s (ones) in it | Find column with at least one non zero element
1 visualizzazione (ultimi 30 giorni)
Mostra commenti meno recenti
Rishi Balasubramanian
il 23 Dic 2020
Risposto: Image Analyst
il 23 Dic 2020
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);
0 Commenti
Risposta accettata
Walter Roberson
il 23 Dic 2020
count = sum(H);
idx = find(count);
[~, relidx] = min(count(idx)) ;
mincol = idx(relidx);
2 Commenti
Walter Roberson
il 23 Dic 2020
count = sum(H);
count(count==0) = nan;
[~, mincol] = min(count) ;
Più risposte (1)
Image Analyst
il 23 Dic 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
0 Commenti
Vedere anche
Categorie
Scopri di più su Multidimensional Arrays in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!