基于列表生成随机数是否可行?
A = [8 1 5; 1 4 2; 7 5 2];
Max = 5
B = randi(Max);
现在我有一部分代码产生一个随机数。我正在寻找从数字列表中产生一个随机数,在这种情况下,第一行中列出的数字(8 1 5
)。基于列表生成随机数是否可行?
而不是使用randi
是否有另一个函数会随机生成第一行中列出的数字之一,也符合Max
条件?
从你指定的内容,我建议如下:
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)))
希望这给一些想法,
最简单的方法是使用arrayfun
:
B = arrayfun(@randi, A(1,:))
谢谢!这可以很容易地修改,只返回该行中的一个数字? –
@JahnnyT:你的意思是'arrayfun(@randi,A(1,[2 2 2]))''? –
不,我期待随机输出一个变量而不是三个。在这种情况下'8 1 5'。还有它不超过最大= 5的标准。因此,这个例子的随机数可以是'1或5'。 –
谢谢!我不知道randperm的功能。 –