How to shuffle rows of a matrix, say order 4, with the help of set having 4 elements, several times?

2 views (last 30 days)
Abdul Gaffar
Abdul Gaffar on 7 Feb 2018
Commented: Abdul Gaffar on 7 Feb 2018
Let
R=[1,2,3,4;5,6,7,8;9,10, 11,12;13,14,15,16];
k=[3,4,1,2];
for i=1:4
R1(i,:)=R(k(i),:);
end
for i=1:4
R2(i,:)=R1(k(i),:);
end
for i=1:4
R3(i,:)=R2(k(i),:);
end
R3
My output will be R3. I want to do this using loop
  3 Comments

Sign in to comment.

Accepted Answer

Jan
Jan on 7 Feb 2018
Edited: Jan on 7 Feb 2018
The for i loop over k is not needed:
R = [1,2,3,4; 5,6,7,8; 9,10,11,12; 13,14,15,16];
k = [3,4,1,2];
for i = 1:3
R = R(k, :);
end
Now R is modified inplace.
If you R is huge, it is cheaper to shuffle an index vector instead:
k = [3,4,1,2];
v = 1:4;
for i = 1:3
v = v(k);
end
Rfinal = R(v, :)
  3 Comments

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!