function xAvg = randomAvgs(x,w,nVals,nAvgs)
% Returns a vector of nAvgs averages, each of nVals values, taken randomly
% from a vector of possible values x, with weights w
% Input
%   x      : vector of possible values
%   w      : vector of weights, with same lenght as x
%   nVals  : number of values in each average
%   nAvgs  : number of averages to be calculated (lenght of vector xAvg)
% Output 
%   xAvg   : row vector, of length nAvgs, with random averages
% Usage
%   xAvg = randomAvgs(x,w,nVals,nAvgs)
% Author
%   Jose M Soler. Nov.2016

% Find vector of accumulated probabilities p_i=w_i/sum(w)
pSum = cumsum(w) / sum(w);
    
% Find averages
for iAvg = 1:nAvgs
    for iVal = 1:nVals
        % Select randomly one x value 
        ix(iVal) = find(rand<pSum,1);  % index of the selected value
    end
    % Find average
    xAvg(iAvg) = sum(x(ix))/nVals;
end
    
end % function
