【问题标题】:Ordered random numbers in MatlabMatlab中的有序随机数
【发布时间】:2018-02-01 16:15:39
【问题描述】:

我正在尝试使用 Matlab 的 randperm 并调用 randperm = 5 生成 1 到 5 之间的随机数。

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

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

我需要排列向量,使 4 和 5 始终彼此相邻,而 2 始终在 1 和 3 之间......例如[3 2 1 4 5][4 5 1 2 3]

所以基本上我有两个长度不等的“块” - 1 2 34 5。块的顺序并不那么重要,只是 4 和 5 最终在一起,而 2 在 1 和 3 之间。

我基本上只能有4种可能的组合:

[1 2 3 4 5]

[3 2 1 4 5]

[4 5 1 2 3]

[4 5 3 2 1]

有人知道我该怎么做吗?

谢谢

【问题讨论】:

  • 两个块都使用randperm,如何为它们建立索引使用randperm(2)
  • 由于您的可能组合数量非常有限,请从这些组合中创建一个数组,然后使用randi从中随机选择一行。
  • 一定要4 5吗?您所有可能的组合均未显示5 4
  • @Adriaan:我数了 8 种可能性:上面的四种,再加上另外四种,4 和 5 交换了。

标签: arrays matlab random


【解决方案1】:

我不确定您是否想要一个能够以某种方式推广到更大问题的解决方案,但根据您在上面描述问题的方式,您似乎只会有 8 种可能的组合来满足您的限制:

possible = [1 2 3 4 5; ...
            1 2 3 5 4; ...
            3 2 1 4 5; ...
            3 2 1 5 4; ...
            4 5 1 2 3; ...
            5 4 1 2 3; ...
            4 5 3 2 1; ...
            5 4 3 2 1];

您现在可以使用randi 随机选择这些行中的一个或多个,甚至可以创建一个anonymous function 来为您执行此操作:

randPattern = @(n) possible(randi(size(possible, 1), [1 n]), :)

这允许您随机选择 5 个模式(每行一个):

>> patternMat = randPattern(5)

patternMat =

     4     5     3     2     1
     3     2     1     4     5
     4     5     3     2     1
     1     2     3     5     4
     5     4     3     2     1

【讨论】:

    【解决方案2】:

    您可以生成每个块并打乱每个块,然后将它们设置为元胞数组的成员并打乱元胞数组,最后将元胞数组转换为向量。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-16
      • 2018-01-28
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多