MATLAB: Choose one out of every 8 elements randomly

random sampling

I have a 1xm matrix and I want to choose one out of every 8 elements randomly, I can think of ways using for loops but I was hoping for a solution without for loops and efficient in terms of speed. Thanks

Best Answer

m = 21;
A = (1:m)+0.314;
nof8 = ceil(m/8);
randSelect = randi([1 8],1,nof8);
inds = randSelect+(0:nof8-1)*8;
% if m is not a multiple of 8 the last samples must get special treatment
% the simplest solution is to limit the indices in inds to the m
inds(end)=min(inds(end),m);
% but this leads to a non-uniform distribution for the last selection.
selectedElements = A(inds)
A solution with an uniform distribution for all cases was suggested from Guillaume:
randselect = randi(8, 1, floor(numel(A)/8));
if mod(numel(A), 8) > 0
randselect = [randselect, randi(mod(numel(A), 8))];
end
selectedvalues = A(randselect + (0:ceil(numel(A)/8)-1)*8)