【问题标题】:How can I use MATLAB program to create a new column array with random arrangements of 1, 2 and 3? [duplicate]如何使用 MATLAB 程序创建一个随机排列为 1、2 和 3 的新列数组? [复制]
【发布时间】:2012-12-29 06:12:05
【问题描述】:

可能重复:
Generate random number with given probability matlab

我需要创建一个随机分配数字 1、2 和 3 的列向量。但是我需要能够控制这 3 个数字中每个 oif 的出现百分比。

例如,我有一个100 x 1 列向量,我希望随机分配数字 1 的 30 个、数字 2 的 50 个和数字 3 的 20 个。

【问题讨论】:

    标签: matlab random


    【解决方案1】:

    我不确定您是否可以使用 randrandi 函数来做到这一点。

    也许你可以写一个像这样的小模块:

    bit1 = 1 * ones(1,20);
    bit2 = 2 * ones(1,50);
    bit3 = 3 * ones(1,30);
    
    bits = [bit1 bit2 bit3];
    randbits = bits(:, randperm(length(bits)))
    

    【讨论】:

    • 嗨,谢谢...如果我需要运行这个随机化 30 次怎么办。因此,我如何创建一个 30x100 矩阵,它有 30 个不同的随机序列,而不是重复随机命令 30 次。抱歉,我对 MATLAB 还是很陌生。
    • 您必须在该条件中使用循环。另一种方法是用 one(30,20) 替换 one(1,20)。然后您需要使用horzcatvertcat 连接数组
    【解决方案2】:

    您可以使用每个数字的百分比的CDF (cumulative destribution function) 来做到这一点。

    pdf = [ 30 50 20 ]/100; % the prob. distribution fun. of the samples
    cdf = cumsum( pdf );
    % I assume here all entries of the PDF are positive and sum(pdf)==1
    % If this is not the case, you may normalize pdf to sum to 1.
    

    采样本身

    n = 100; % number of samples required
    v = rand(n,1); % uniformly samples
    tmp = bsxfun( @le, v, cdf );
    [~, r] = max( tmp, [], 2 );
    

    正如@Dan 所观察到的(见下面的评论),最后一行可以替换为

    r = numel(pdf) + 1 - sum( tmp, 2 );
    

    向量r 是整数1,2,3 的随机向量,应该满足所需的pdf

    【讨论】:

    • 是 [~, r] = max( tmp, [], 2 );与 4 - sum(tmp, 2) 相同?
    • @Dan - 确实!不错的...
    • 谢谢,只是检查我理解为我没有 matlab。顺便说一句,这是一个很好的解决方案。
    猜你喜欢
    • 2021-12-28
    • 2018-11-19
    • 2014-02-13
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    相关资源
    最近更新 更多