function index = findMax(M)
%FINDMAX Find maximum element in matrix.
%   INDEX = FINDMAX(M) finds the index of the first element with the
%   maximum value in the matrix M. If M is 2-dimensional, maxima are
%   looked for along the 2nd dimension.

%   Author: Damien Teney

if numel(M) == length(M) % M is a vector
  index = find(M == max(M), 1, 'first');

elseif ndims(M) == 2 % M is a matrix
  index = zeros(1, size(M, 1));
  maxVals = bsxfun(@eq, M, max(M, [], 2)) ;
  for i = 1:size(M, 1) % We look for maxima along the the 2nd dimension (arbitrary choice)
    index(i) = find(maxVals(i, :), 1, 'first');
  end

else
  error('Not supported !');
end
