Reputation: 221
I would like to find the numbers that are not most frequent from a matrix for every column in matlab
for eg..,
a = [3 3 1 4; 0 0 1 1; 0 1 2 4]
The answer I expect is
[3 3 2 1]
Any help would be greatly appreciated.
Thanks in advance.
Regards,
Raja
Upvotes: 3
Views: 71
Reputation: 221544
Assuming that in case of a tie
for the minimum count in a column, you would settle for the minimum valued element, this is a bsxfun
based solution code to solve it -
%%// 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).'
Alternative approach using 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
Upvotes: 2
Reputation: 112659
This gives the lowest value in case of a tie:
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
Upvotes: 1