gpt4 book ai didi

matlab - 如何在 MATLAB 中生成 0 或 1 的随机整数

转载 作者:太空宇宙 更新时间:2023-11-03 19:39:17 27 4
gpt4 key购买 nike

我在 MATLAB 文档中搜索了如何生成 0 或 1 的随机整数。

我偶然发现了 randint 和 randi 这两个函数。randint 在我的 MATLAB 版本中似乎已被弃用,尽管它在在线文档中并且 randi 似乎只创建介于 1 和指定的 imax 值之间的随机数。

我什至创建了自己的 randint 函数来解决这个问题,尽管它在我的程序中运行效率不高,因为它用于大型数据集:

function [ints] = randint(m,n)
ints = round(rand(m,n));
end

是否有内置函数可以创建一个 0 或 1 的随机整数,或者是否有更有效的方法在 MATLAB 中创建这样的函数?

最佳答案

这似乎快了一点:

result = rand(m,n)<.5;

或者,如果您需要 double 的结果:

result = double(rand(m,n)<.5);

m = 100n = 1e5 的示例(Matlab 2010b):

>> tic, round(rand(m,n)); toc
Elapsed time is 0.494488 seconds.

>> tic, randi([0 1], m,n); toc
Elapsed time is 0.565805 seconds.

>> tic, rand(m,n)<.5; toc
Elapsed time is 0.365703 seconds.

>> tic, double(rand(m,n)<.5); toc
Elapsed time is 0.445467 seconds.

关于matlab - 如何在 MATLAB 中生成 0 或 1 的随机整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25041698/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com