Find the column with the least number of 1s (ones) in it | Find column with at least one non zero element
2 views (last 30 days)
Show older comments
Rishi Balasubramanian
on 23 Dec 2020
Answered: Image Analyst
on 23 Dec 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 Comments
Accepted Answer
Walter Roberson
on 23 Dec 2020
count = sum(H);
idx = find(count);
[~, relidx] = min(count(idx)) ;
mincol = idx(relidx);
2 Comments
Walter Roberson
on 23 Dec 2020
count = sum(H);
count(count==0) = nan;
[~, mincol] = min(count) ;
More Answers (1)
Image Analyst
on 23 Dec 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 Comments
See Also
Categories
Find more on Multidimensional Arrays 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!