Random shuffle of vector elements

조회 수: 141 (최근 30일)
Premysl Stastny
Premysl Stastny 2021년 10월 5일
댓글: Fangjun Jiang 2021년 10월 5일
Hello,
How to randomly shuffle all elements of the vector except the first and last position?
For example:
I have vector A=[5 1.5 1.6 1.7 5] and I want to randomly shuffle 2nd, 3rd 4th element while the 1st and the last will stay the same.
Thank you

채택된 답변

Constantino Carlos Reyes-Aldasoro
This can be easily done by addressing the vector correctly. First you need a random order to shuffle your elements. You can do that by using rand and then sort:
[a,b]=sort(rand(1,3))
a = 1×3
0.0591 0.2095 0.2737
b = 1×3
3 2 1
so b will be the order. Now you need to use that to re-order your vector, let's call the new vector A2:
A=[5 1.5 1.6 1.7 5];
A2 = [A(1) A(b+1) A(end)]
A2 = 1×5
5.0000 1.7000 1.6000 1.5000 5.0000
Now you have a new vector with the first and last same as they were, but 2:4 have been randomly shuffled.
Hope this solves your question.

추가 답변 (1개)

Fangjun Jiang
Fangjun Jiang 2021년 10월 5일
p=randperm(3);
index=[1,1+p,5];
b=A(index);
  댓글 수: 1
Fangjun Jiang
Fangjun Jiang 2021년 10월 5일
do it in one shot
p=perms(2:4);
index=[ones(6,1), p, 5*ones(6,1)];
b=A(index)

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

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by