I’m not a MATLAB expert myself, but I had to code the roulette wheel selection algorithm, once again, this time in the MATLAB programming language. It complements this post, so I thought I could share it:
% --------------------------------------------------------- % Roulette Wheel Selection Algorithm. A set of weights % represents the probability of selection of each % individual in a group of choices. It returns the index % of the chosen individual. % Usage example: % fortune_wheel ([1 5 3 15 8 1]) % most probable result is 4 (weights 15) % --------------------------------------------------------- function choice = fortune_wheel(weights) accumulation = cumsum(weights); p = rand() * accumulation(end); chosen_index = -1; for index = 1 : length(accumulation) if (accumulation(index) > p) chosen_index = index; break; end end choice = chosen_index;
It can be probably rewritten in a nice MATLAB way, but it’s useful as is.