MATLAB: Choose n out of every 4 elements randomly.

matrix manipulation

I have a 1 by 124 matrix and I want to choose 'n' where n can be 1, 2or 3 from every 4 elements randomly.
This is my code but currently it selects 1 every 4. How can I make it generic, that is it selects 2 or 3 out of 4.
m = length(elements);
nof4 = m/4;
randSelect = randi([1 4],1,nof4);
inds = randSelect+(0:nof4-1)*4;
output= elements(inds);
Thanks

Best Answer

Try this:
% Create sample data.
m = randi(9, 1, 124);
% Define how many from each block of 4 you want to take
n = 3;
% Reshape m to have 4 columns and 31 rows
mReshaped = reshape(m, [], 4);
[rows, columns] = size(mReshaped);
% Preallocate an output array
out = zeros(rows, n);
for row = 1 : size(mReshaped, 1)
% Get random column indexes.
randomColumns = randperm(4, n)
% Extract those elements into our output matrix.
out(row,:) = mReshaped(row,randomColumns);
end
out % Print to command window.