【问题标题】:Is it feasible to generate a random number based on a list?根据列表生成随机数是否可行?
【发布时间】:2012-10-13 17:43:34
【问题描述】:
A = [8 1 5; 1 4 2; 7 5 2];

Max = 5

B = randi(Max);

现在我有一部分代码可以生成一个随机数。我希望从数字列表中生成一个随机数,在本例中是第一行中列出的数字 (8 1 5)。

除了使用 randi 之外,还有其他函数可以随机生成第一行中列出的数字之一,同时满足 Max 标准吗?

【问题讨论】:

    标签: matlab random matrix


    【解决方案1】:

    根据您指定的内容,我建议如下:

    A = [8 1 5; 1 4 2; 7 5 2];
    
    % get a random number from row 1
    index = randperm(length(A(1,:)));
    number = A(1,index(1))
    
    % get a randome number from row 1 that does not exceed Max
    max = 5;
    condition = find(A(1,:) <= max);
    index = randperm(length(A(1,condition)));
    number = A( 1, condition(index(1)))
    

    希望这能提供一些想法,

    【讨论】:

    • 谢谢!我不知道 randperm 函数。
    【解决方案2】:

    最简单的方法是使用arrayfun

    B = arrayfun(@randi, A(1,:))
    

    【讨论】:

    • 谢谢!这可以很容易地修改为只返回该行中的一个数字吗?
    • @JahnnyT:你的意思是arrayfun(@randi, A(1,[2 2 2]))
    • 不,我希望随机输出一个变量而不是三个变量。在这种情况下8 1 5。还有标准是它没有超过Max = 5。因此,这个例子中的随机数可以是1 or 5
    • @JahnnyT:啊,你的意思是:输出 8、1 或 5?
    • 正确。如果可能,小于或等于Max = 5
    猜你喜欢
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 2018-05-23
    • 2020-06-29
    • 1970-01-01
    • 2021-03-23
    相关资源
    最近更新 更多