【问题标题】:Generating a random Integer between 1 and 3 excluding a variable生成 1 到 3 之间的随机整数,不包括变量
【发布时间】:2014-04-09 02:52:13
【问题描述】:

使用 Matlab 我必须以相等的概率生成 1 到 3 之间的随机整数两次。

A=round(((rand(1)*2)+1))
B=round(((rand(1)*2)+1))

然后我必须生成另一个随机整数 C,介于 1 和 3 之间,不能与变量 A 和 B 相同。

即A = 1,B = 3,C = 2 要么 A = 2,B=2,C 可以等于 1 或 3。

最好使用“if”函数。

【问题讨论】:

  • 你的意思是没有 IF,不是吗?

标签: matlab random integer probability rounding


【解决方案1】:
A = ceil(3*rand); %// 1,2,3 with equal probability
B = ceil(3*rand); %// 1,2,3 with equal probability, independent from A
notAB = setdiff(1:3,union(A,B)); %// allowed values for C
indC = ceil(rand*numel(notAB)); %// select one of them, with equal probability
C = notAB(indC);

在这种情况下,显式编写所有允许的组合并随机选择其中一个可能会更简单:

template = [1 1 2
            1 1 3
            1 2 3
            1 3 2
            2 1 3
            2 2 1
            2 2 3
            2 3 1
            3 1 2
            3 2 1
            3 3 1
            3 3 2];
ind = ceil(rand*size(template,1));
A = template(ind,1);
B = template(ind,2);
C = template(ind,3);

【讨论】:

  • @Edric 因为旧版本的 Matlab 没有它。由于OP使用rand,我假设他们可能没有randi
【解决方案2】:

您应该使用RANDI 来生成随机整数。

AB = randi([1, 3], 1, 2); % Generate A and B at the same time
while true
    C = randi([1 3]);     % Make C
    if ~ismember(C, AB)   % Is C ok?
        break;            % Then terminate the loop.
    end
end

或者这是另一种没有循环的方法。

AB = randi([1, 3], 1, 2);               % Generate A and B at the same time
possibleC = setdiff(AB, 1:3);           % All valid values of C
C = possibleC(randi(numel(possibleC))); % pick one at random.

【讨论】:

    【解决方案3】:

    首先

    A=round(((rand(1)*2)+1))
    

    将选择 1 25% 的时间、2 50% 的时间和 3 25% 的时间。 不是均匀分布。

    你真正想要的是

    A=floor(((rand*3)+1));
    

    为了证明这一点,请尝试 A=round(((rand(10000,1)*2)+1)) 并观察 sum(A==1)/10000sum(A==2)/10000 等的值...

    现在获取C试试

    S = randperm(3);
    

    并按照 Divakar 的建议进行,即

    C = S(S~=A & S~=B);
    C = C(1);
    

    【讨论】:

      【解决方案4】:

      试试这个 -

      lin_ind = 1:3;
      out = lin_ind(lin_ind~=A & lin_ind~=B);
      C = out(1)
      

      【讨论】:

      • 这将偏向于在A==B 的情况下为C 选择较低的值。而是使用lin_ind = randperm(3)
      • 你是对的。我实际上根本没有考虑概率。我只是假设概率标准仅适用于 A 和 B,这将由 OP 的代码处理。
      猜你喜欢
      • 2014-06-23
      • 1970-01-01
      • 2014-04-11
      • 1970-01-01
      • 2011-08-19
      • 2013-01-02
      • 1970-01-01
      • 2011-04-29
      • 2021-11-24
      相关资源
      最近更新 更多