Random shuffle of vector elements
139 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
Constantino Carlos Reyes-Aldasoro
2021-10-5
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))
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)]
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.
0 个评论
更多回答(1 个)
Fangjun Jiang
2021-10-5
p=randperm(3);
index=[1,1+p,5];
b=A(index);
1 个评论
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 Center 和 File Exchange 中查找有关 Logical 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!