Matlab中的有序随机数 [英] Ordered random numbers in Matlab
问题描述
我正在尝试使用Matlab的randperm
并调用randperm = 5
来生成1到5之间的随机数.
I am trying to generate random numbers between 1 and 5 using Matlab's randperm
and calling randperm = 5
.
每次给我一个不同的数组,例如:
Each time this gives me a different array let's say for example:
x = randperm(5)
x = [3 2 4 1 5]
我需要对向量进行排列,以使4和5总是彼此相邻,而2总是在1和3之间...例如[3 2 1 4 5]
或[4 5 1 2 3]
.
I need the vector to be arranged such that 4 and 5 are always next to each other and 2 is always between 1 and 3... so for e.g. [3 2 1 4 5]
or [4 5 1 2 3]
.
所以从本质上讲,我有两个长度不相等的块"-1 2 3
和4 5
.块的顺序不是很重要,只是4& ;; 5个在一起,2个在1到3之间.
So essentially I have two "blocks" of unequal length - 1 2 3
and 4 5
. The order of the blocks is not so important, just that 4 & 5 end up together and 2 in between 1 and 3.
我基本上只能有4种可能的组合:
I can basically only have 4 possible combinations:
[1 2 3 4 5]
[3 2 1 4 5]
[4 5 1 2 3]
[4 5 3 2 1]
有人知道我该怎么做吗?
Does anyone know how I can do this?
谢谢
推荐答案
您可以生成每个块并对其进行随机排序,然后将它们设置为单元格数组的成员,然后对单元格进行重新排序,最后将单元格数组转换为向量
You can generate each block and shuffle each one then and set them as members of a cell array and shuffle the cell array and finally convert the cell array to a vector.
b45=[4 5]; % block 1
b13=[1 3]; % block 2
r45 = randperm(2); % indices for shuffling block 1
r13 = randperm(2); % indices for shuffling block 2
r15 = randperm(2); % indices for shuffling the cell
blocks = {b45(r45) [b13(r13(1)) 2 b13(r13(2))]}; % shuffle each block and set them a members of a cell array
result = [blocks{r15}] % shuffle the cell and convert to a vector
这篇关于Matlab中的有序随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!