Find the column with the least number of 1s (ones) in it | Find column with at least one non zero element
조회 수: 1 (최근 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);
댓글 수: 2
Walter Roberson
2020년 12월 23일
count = sum(H);
count(count==0) = nan;
[~, mincol] = min(count) ;
추가 답변 (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!