How to shuffle rows of a matrix, say order 4, with the help of set having 4 elements, several times?
1 次查看(过去 30 天)
显示 更早的评论
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
采纳的回答
Jan
2018-2-7
编辑:Jan
2018-2-7
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 个评论
Jan
2018-2-7
编辑:Jan
2018-2-7
@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?
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!