Search code examples
matlabvectorfillstatistics-bootstrap

Fill consecutive elements of a vector fast


This is a block bootstrap code in Matlab used for generating blocks of dates in a random order. First a random vector consists of the starting elements of a block and is followed bei 11 zeros at first. The random values represent the element of a date vector.

randVector(1:12:253,:) = ceil(252*rand(ceil(253/12),nmbBootstrap)); 

The for loop should now fill the consecutive elements up to the next existing value.

for ii = 1:12-1
    randVector(1+ii:12:253,:) = mod(randVector(ii:12:252,:),252)+1; 
end

Finally convert the random vector into real dates

randDates = dates(randVector(1:end-1,:));

How can the for loop be replaced by vectorizing, since it takes a lot of time when using big nmbBootstrap values?


Solution

  • Because of the small number of iterations of the loop vectorizing does not offer a significant advantage in this case. Would it be way more iterations, a possible solution is:

    nmbBootstrap = 50000;
    randVector = rectpulse(ceil(252*rand(ceil(253/12),nmbBootstrap)),12);
    additive = repmat((0:11)',ceil(253/12),nmbBootstrap);
    randVector = mod(randVector + additive-1,252)+1;