matlab - 最接近第一个索引的每行中的众数 - MATLAB

标签 matlab matrix

我有一个数字矩阵,我想找到每一行的模式,但是如果有多种模式,我想使用最接近索引 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

最佳答案

Vectorized方法 bsxfun带你回家-

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

关于matlab - 最接近第一个索引的每行中的众数 - MATLAB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29292158/

相关文章:

c++ - 按光栅顺序阅读?

algorithm - 查找是否可以从字符矩阵中获取字符串

matlab - MATLAB 和卡方检验的拟合优度

matlab将文件解析为元胞数组

matlab - 对行求和,但删除每行中的不同项

python - 如何删除numpy中具有相同值的列

c++ - 使用自动时 Eigen3 随机矩阵更改值

algorithm - 使用变换矩阵围绕任意点旋转

c++ - 将 Matlab 数组移植到 C/C++

matlab - 求元素间二阶差分绝对值的均值