【发布时间】:2014-10-09 01:13:00
【问题描述】:
我想从 matlab 中每一列的矩阵中找出不是最频繁的数字
例如..,
a = [3 3 1 4; 0 0 1 1; 0 1 2 4]
我期待的答案是
[3 3 2 1]
任何帮助将不胜感激。
提前致谢。
问候,
拉贾
【问题讨论】:
-
在平局的情况下你想如何选择(例如第2列)?
我想从 matlab 中每一列的矩阵中找出不是最频繁的数字
例如..,
a = [3 3 1 4; 0 0 1 1; 0 1 2 4]
我期待的答案是
[3 3 2 1]
任何帮助将不胜感激。
提前致谢。
问候,
拉贾
【问题讨论】:
假设如果tie 用于列中的最小计数,您将选择最小值元素,这是一个基于 bsxfun 的解决方案代码来解决它 -
%%// Unique values across the entire matrix
unqval = unique(a(:))
%// Counts of those unique values for each column
counts = sum(bsxfun(@eq,a,permute(unqval,[3 2 1])),1)
%// Make the zero counts as NaNs as they don't exist at all for a column
counts(counts==0)=NaN
%// Indices for the minimum counts with the minimum valued element in a tie-case
[~,v2] = nanmin(permute(counts,[3 2 1]))
%// Minimum count elements of input for each coloumn, to form the desired output
out = unqval(v2).'
使用for-loop 的替代方法-
alf(1,size(a,2))=0; %// alf would be the desired output
for k = 1:size(a,2)
unqval = unique(a(:,k));
[~,ind] = min(histc(a(:,k),unqval));
alf(k) = unqval(ind);
end
【讨论】:
这给出了平局时的最低值:
u = unique(a(:)).'; %'// find unique values of a
h = histc(a, u); %// count for each value, in each column
h(h==0) = inf; %// mark non-present values
[~, r] = min(h); %// find first (i.e. lowest) value with minimum count
result = u(r); %// build result
【讨论】:
histc(a, u),因为我认为histc 仅适用于向量,但显然矩阵也适用哦!!这一个必须是OP的选择!当然 +1。
unique + histc 在各种应用程序中的应用如此广泛,Mathworks 的人可能会考虑制作一个单独的函数来结合这些! :)
accumarray,第二个参数是矩阵:-)
for 循环方法(我+1),它一次只处理一列,因此可能更节省内存。如果内存不是问题,可能很难加快速度