Alex Musk
Alex Musk

Reputation: 158

Mode in each row closest to first index - MATLAB

I have a matrix of numbers and I want to find the mode of each row, however I want to use the item closest to index 1 if there are multiple modes (built in function just uses the smallest value)

for example:

% 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)

actual answer

1
1
1
1

required answer

1
4
1
2

Upvotes: 2

Views: 70

Answers (1)

Divakar
Divakar

Reputation: 221574

Vectorized appproach with bsxfun to take you home -

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))))

Sample run -

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

Upvotes: 2

Related Questions