arrays - 随机数对 Matlab

标签 arrays matlab random psychtoolbox

我正在尝试使用 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/

相关文章:

matlab - matlab中的EEG带通滤波器

matlab - 如何在给定非零元素位置的 MATLAB 中创建稀疏矩阵

matlab - 处理类导致创建新对象时属性被覆盖

python:具有概率的随机样本

python - 生成随机分布时转换为 int - Python

arrays - 为什么在数组扩展中使用 Stride 非法创建临时数组

php - Laravel - 更新输入文件中上传的文件

c - 使用函数将 char 数组解析为数组

java - 具有不同表达式类型的嵌套开关: ArrayIndexOutOfBoundsException -4

perl - rand() 在 perl 中不是那么随机