function [val, idx] = fairmax(x)
%FAIRMAX    Same as built-in max(), except breaks ties randomly.
%   [val, idx] = fairmax(x) takes a vector as an argument and returns
%   the same output as the built-in function max (see 'help max' for details.)
%   with two output parameters, except that where the maximum value occurs
%   at more than one position in the  vector, the index is chosen randomly
%   from these positions as opposed to just choosing the first occurance.

%   MATPOWER
%   $Id: fairmax.m,v 1.3 2004/08/23 20:56:17 ray Exp $
%   by Ray Zimmerman, PSERC Cornell
%   Copyright (c) 1996-2004 by Power System Engineering Research Center (PSERC)
%   See http://www.pserc.cornell.edu/matpower/ for more info.

val = max(x);               %% find max value
i   = find(x == val);       %% find all positions where this occurs
n   = length(i);            %% number of occurences
idx = i( fix(n*rand)+1 );   %% select index randomly among occurances

return;
