function RSV = RSanalysis(xV,dtV)
% RSV = RSanalysis(xV,dtV)
% RSanalysis computes the Hurst exponent for a given time series 'xV' 
% using the method of rescaled range analysis (R/S analysis).
% INPUTS:
% - xV      : The given scalar time series (vector of size n x 1).
% - dtV     : the array of increasing time segment lengths.
% OUTPUTS
% - RSV     : The vector of average fluctuations (ratio of range over SD).  

n = length(xV);
ndt = length(dtV);
RSV = NaN*ones(ndt,1);
for i=1:ndt
    w = dtV(i);
    nseg=floor(n/w);  % number of segments of the given length
    xM=reshape(xV(1:w*nseg),w,nseg); % a segment at each column
    isegV=find(std(xM,1)~=0); % check for segments with all values equal (no variance)
    if ~isempty(isegV) 
        xM=xM(:,isegV); % make calculations only on those segments with non-zero variance
        mxV = mean(xM);
        yM=cumsum(xM-kron(mxV,ones(w,1)),1);
        RSV(i)=mean(range(yM)./std(xM,1));
    end
end
