我正在尝试使用 Matlab 的 randperm
并调用 randperm = 6
生成 1 到 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
中做某事时,这个顺序很重要。
是否可以有随机顺序的“ block ”?我不知道该怎么做。
谢谢
最佳答案
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 = 总数
block = 一个 block 中的数字
%Sample run with t=12 and block=3
>> req.'
ans =
10 11 12 4 5 6 1 2 3 7 8 9
编辑:
如果您还希望每个 block 中的数字以随机顺序排列,请在上述代码的最后一行之前添加以下 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
关于arrays - 随机数对 Matlab,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45786911/