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

조회 수: 2 (최근 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
  댓글 수: 3

댓글을 달려면 로그인하십시오.

채택된 답변

Jan
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
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 CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by