function balanced_array=balanced_bootstrap_array_maker(len,num_bootstrap_runs)
%bootstrap with balanced resampling, as suggested by Davison and Hinckley
%checked aug 7/2007

lenvec=1:len;
ordered_array=repmat(lenvec,num_bootstrap_runs,1);
randomized_array=zeros(num_bootstrap_runs,len);

for rowtofill=1:num_bootstrap_runs
    for coltofill=1:len
        %[chosenrow,chosencol]=recursive_search_for_balanced_bootstrap(ordered_array,num_bootstrap_runs,len);        %this is a more fun way to do it but one runs into problems with the stack limit and has to say things like "set(0,'RecursionLimit',1000)" and this seems to lead to crashes
        candidaterow=ceil(rand*num_bootstrap_runs);
		candidatecol=ceil(rand*len);
        while isnan(ordered_array(candidaterow,candidatecol))
            candidaterow=ceil(rand*num_bootstrap_runs);
			candidatecol=ceil(rand*len);
        end
        chosenrow=candidaterow;
        chosencol=candidatecol;
        randomized_array(rowtofill,coltofill)=ordered_array(chosenrow,chosencol);
        ordered_array(chosenrow,chosencol)=nan;
    end
end
balanced_array=sort(randomized_array')';