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 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. See also MAX.
0001 function [val, idx] = fairmax(x) 0002 %FAIRMAX Same as built-in MAX, except breaks ties randomly. 0003 % [VAL, IDX] = FAIRMAX(X) takes a vector as an argument and returns 0004 % the same output as the built-in function MAX with two output 0005 % parameters, except that where the maximum value occurs at more 0006 % than one position in the vector, the index is chosen randomly 0007 % from these positions as opposed to just choosing the first occurance. 0008 % 0009 % See also MAX. 0010 0011 % MATPOWER 0012 % Copyright (c) 1996-2015 by Power System Engineering Research Center (PSERC) 0013 % by Ray Zimmerman, PSERC Cornell 0014 % 0015 % $Id: fairmax.m 2644 2015-03-11 19:34:22Z ray $ 0016 % 0017 % This file is part of MATPOWER. 0018 % Covered by the 3-clause BSD License (see LICENSE file for details). 0019 % See http://www.pserc.cornell.edu/matpower/ for more info. 0020 0021 val = max(x); %% find max value 0022 i = find(x == val); %% find all positions where this occurs 0023 n = length(i); %% number of occurences 0024 idx = i( fix(n*rand)+1 ); %% select index randomly among occurances