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.
hi
thank you
this is useful
🙂
Great Man!
Thank you
try this: instead of the for loop
index = find(accumulation>p,1)
It will give u the index for the first term in accumulation that is larger than p without a loop.
Thanks! I’m not using Matlab anymore, but someone may find that useful.
Could you please explain how the most chosen element is 4th one ?
Because in this line you have done
p = rand() * accumulation(end);
So this means taking a uniformly distributed random number between 0 and 1 and multiplying it by the sum of all weights (accumulation(end))
and then you pick up the first index greater than this value in the accumulation array
How does this ensure that the most chosen element is the 4th one or the most chosen weight is 15 ???
Well, that’s precisely the idea behind this algorithm! Have a look at the original post, here, where there’s a graphic explaining that.
I’m not picking the first index greater than that value, but the index of the first bin the accumulation array which value is greater than that random number!
thank you
Thanks, the Matlab way is to eliminate all looping, you can do that by just taking the absolute minimum and pulling out the index that way.
For example:
accumulation = cumsum(Fitness-min(Fitness));
[ma indivudual_picked]=min(abs(accumulation-rand * accumulation(end)));
indivudual_picked is what you want, also if you have negatives in your fitness they can screw this up so I subtract out the min.
Woa, I’ve not worked with Matlab for a few years, so I’ll believe you 😀
Thanks a lot!
can any variable in the algorithm be changed to get better selection? Can you suggest any other selection algorithm?
Increasing the probability of a given slot of being selected is just a matter of setting a proper weight. I guess it depends on what’s a ‘better selection’. What do you mean?