shuffle blocks of elements in vector?

3 次查看(过去 30 天)
i have for example the following vector:
v = [1;2;3;4;5;6;7;8;9;10;11;12]
now i would like to cut them into blocks of 3 elements in a row and shuffle these blocks. the end result could look like this:
v_shuffled = [1;2;3;10;11;12;7;8;9;4;5;6]
my idea is to somehow store each block as a row vector in a matrix, shuffle these rows and then build a vector out of the shuffled matrix rows. this is what i have so far (code doesnt work)
for i=1:(length(v))/4
u(i,1)=v(4*i);
u(i,2)=v(4*i+1);
u(i,3)=v(4*i+2);
u(i,4)=v(4*i+3);
end
s = u(randperm(size(u,3)),:)
for i=1:length(v)/4
h(4*i,1)=s(i,1);
h(4*i+1,1)=s(i,2);
h(4*i+2,1)=s(i,3);
h(4*i+3,1)=s(i,4);
end
any ideas?

回答(1 个)

Roger Stafford
Roger Stafford 2017-12-7
v = reshape(v,[],3);
v = reshape(v(randperm(size(v,1)),:),[],1);

类别

Help CenterFile Exchange 中查找有关 Simulink Environment Customization 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by