% rw_selc.m - Roulette Wheel Selection
%
%       Syntax:    NewChrIx = rw_selc(Fit, Nsel)
%
%       This function selects a given number of individuals from a
%       population. 
%
% Input Parameters:
%
%		Fit     - A column vector containing the fitness values of the individuals in the population.
%
%		Nsel    - A scalar containing the given number of individuals
%
% Output Parameters:
%
%		NewChrIx- A column vector containing the index of new population,
%		      which is related to original population matrix, shuffled.
%
%
% Author: Yan-Fu Li
% Date:	21-Oct-05


function NewChrIx = rw_selc(Fit,Nsel);

% Identify the population size (Nc)
[Nc,ans] = size(Fit);

Fit = 1./ Fit;

% Perform Stochastic Sampling with Replacement
cumfit  = cumsum(Fit);
trials = cumfit(Nc) .* rand(Nsel, 1);
Mf = cumfit(:, ones(1, Nsel));
Mt = trials(:, ones(1, Nc))';
[NewChrIx, ans] = find(Mt < Mf & ...
                        [ zeros(1, Nsel); Mf(1:Nc-1, :) ] <= Mt);