Ahmed Abobakr
Ahmed Abobakr

Reputation: 1666

Index-wise Mode of 2D arrays

I am wondering how to arrange the input parameters of the mode function in order to calculate the matrix of modes for input 2D matrices in just one line of code..

for example

x=[7 2;5 10]
y=[7 1;8 3 ]
z=[7 2;8 10]

I want mode(x,y,z) gives this output

output=[7 2;8 10]  // these are the most occurring elements in each index

I have done it this way, but it takes around 2 sec with high dimensional matrices, so I am looking for more efficient way to solve it.

for i=1:2
   for j=1:2
      votes=[];
      for k=1:length(arrs)  // arrs is a cell array of matrices
          votes=[votes arrs{1,k}(i,j)]; 
      end
       res(i,j) = mode(votes);
   end
end

Upvotes: 1

Views: 109

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112689

This might be slightly faster than Falimond's answer because it uses two dimensions instead of three:

output = reshape(mode([x(:).'; y(:).'; z(:).'], 1), size(x));

It works by creating a matrix where each row contains the values from of the original matrices ([x(:).'; y(:).'; z(:).']), finding the mode of each column (mode(..., 1)), and reshaping the result into a matrix (reshape(..., size(x))).

Do try with your matrix sizes and Matlab version to find out which is fastest.

Upvotes: 1

Falimond
Falimond

Reputation: 608

Create a 3 dimensional array composed of x,y,z, then call mode along the third dimension to get the desired result.

xyz = cat(3,x,y,z);
ans = mode(xyz,3);

ans =

     7     2
     8    10

Upvotes: 2

Related Questions