我有一个数字矩阵,我想找到每一行的模式,但如果有多种模式(内置函数只使用最小值),我想使用最接近索引1的项目
例如:
% The 2 takes mode of rows instead of columns
mode([1 2 3 4;
4 3 2 1;
1 1 2 2;
2 2 1 1], 2)
实际答案
1
1
1
1
必填答案
1
4
1
2
答案 0 :(得分:2)
Vectorized
带你回家 -
unqA = unique(A) %// Unique values in A
pos = bsxfun(@eq,A,permute(unqA,[3 2 1])) %// positions of unique values in A
count_pos = sum(pos,2)%// Count of occurrences for each unqA in each row of A
max_count = max(count_pos,[],3) %// Count of max occurances in each row of A
%// Mask pos with the max counts only
mask = bsxfun(@eq,max_count,count_pos)
max_only_pos = bsxfun(@and,mask,pos)
%// Get indices of max counts for in each row & set the invalids to Inf as
%// we need to use min later on. This min operation would correspond to finding
%// the indices closest to 1 as per problem requirements.
[valid,max_idx] = max(max_only_pos,[],2)
max_idx(~valid)=Inf
%// Find min indices & use them as column indices to index into each row of A
out = A(sub2ind(size(A),[1:size(A,1)].',squeeze(min(max_idx,[],3))))
示例运行 -
A =
2 3 2 4 4 4 5
5 1 4 4 1 5 5
2 1 5 1 5 4 5
5 3 3 2 2 5 4
4 2 3 1 2 4 1
out =
4
5
5
5
4