2

我正在尝试使用 Matlabrandperm和调用生成 1 到 6 之间的随机数randperm = 6

每次这给我一个不同的数组,例如:

x = randperm(6)
x = [3 2 4 1 5 6]

我想知道是否可以创建成对的随机数,最终得到x如下结果:

x = [3 4 1 2 5 6]

我需要排列向量,使 1 和 2 始终彼此相邻,3 和 4 彼此相邻,5 和 6 彼此相邻。当我在做某事时Psychtoolbox,这个顺序很重要。

是否有可能有随机顺序的“块”?我不知道该怎么做。

谢谢

4

2 回答 2

4
x=1:block:t ;    %Numbers
req = bsxfun(@plus, x(randperm(t/block)),(0:block-1).');  %generating random blocks of #
%or req=x(randperm(t/block))+(0:block-1).' ; if you have MATLAB R2016b or later
req=req(:);      %reshape

其中,
t = 总数
块 = 一个块中的数字

%Sample run with t=12 and block=3
>> req.'

ans =

    10    11    12     4     5     6     1     2     3     7     8     9

编辑:如果您还希望每个块中的数字以随机顺序排列,请在上述代码的最后一行之前
添加以下 3 行:

[~, idx] = sort(rand(block,t/block));              %generating indices for shuffling
idx=bsxfun(@plus,idx,0:block:(t/block-1)*block);   %shuffled linear indices
req=req(idx);                                      %shuffled matrix

%Sample run with t=12 and block=3
req.'

ans =

     9     8     7     2     3     1    12    10    11     5     6     4
于 2017-08-20T21:59:50.420 回答
3

我可以看到一个简单的 3 步过程来获得您想要的输出:

  1. 生产2*randperm(3)
  2. 将值加倍
  3. randperm(2)-2(随机排序的一对(-1,0))添加到每一对。

在代码中:

x = randperm(3)
y = 2*x([1 1 2 2 3 3])
z = y + ([randperm(2),randperm(2),randperm(2)]-2)

结果

x = 3 1 2
y = 6 6 2 2 4 4
z = 6 5 2 1 3 4
于 2017-08-20T21:35:19.623 回答