Find the column with the least number of 1s (ones) in it | Find column with at least one non zero element
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2020-12-23
count = sum(H);
idx = find(count);
[~, relidx] = min(count(idx)) ;
mincol = idx(relidx);
更多回答(1 个)
Image Analyst
2020-12-23
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!