How to shuffle rows of a matrix, say order 4, with the help of set having 4 elements, several times?
1 view (last 30 days)
Show older comments
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
Accepted Answer
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
Jan
on 7 Feb 2018
Edited: Jan
on 7 Feb 2018
@ABDUL: And this is exactly what my code does. Did you try it?
R = randi([1,10], 4, 4)
k = [3,4,1,2]
R = R(k, :)
R = R(k, :)
R = R(k, :)
Now the rows of R are shuffled according to k 3 times. Because the 1st and 3rd, as well as 2nd an 4th rows are swapped, the sequence of R is repeating. But for longer k there will be more states.
The same in a loop:
for j = 1:3
R = R(k, :)
end
The line
R = R(k, :)
is just a simpler version of
for i = 1:4
R(i, :) = R(k(i), :);
end
As far as I understand your question, you do not need R1 and R2, so I've overwritten R.
Applying the permutation to the index vector is more efficient, because you do not access the complete matrix R in each iteration and the result is the same.
What is the different to what you want? Do you want to change the index vector k in each iteration?
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!