Say if I have a vector of [1 2 3 4 5 6 7 8 9 10], I want to pick a random number of every three element of the vector, so the resulting vector could be [1 4 9 10] or [2 4 8 10] etc.
What would be the best way to do that?
Here's one vectorized approach making use of linear indexing -
function out = pick_one_everyN(a, N)
n = ceil(numel(a)/N);
c = randi(N,1,n);
c(end) = randi(mod(numel(a)-1,N)+1,1);
out = a((0:n-1)*N + c);
Sample runs -
>> a = [1 2 3 4 5 6 7 8 9 10];
>> pick_one_everyN(a, 3)
ans =
3 6 7 10
>> pick_one_everyN(a, 4)
ans =
4 5 9
>> pick_one_everyN(a, 5)
ans =
3 7