如何在MATLAB中生成0或1的随机整数 [英] How to generate a random integer that is either 0 or 1 in MATLAB

查看:1740
本文介绍了如何在MATLAB中生成0或1的随机整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I searched the MATLAB documentation for how to generate a random integer that is either a 0 or a 1.

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

I stumbled upon the two functions randint and randi. randint appears to be deprecated in my version of MATLAB although it is in the documentation online and randi appears to only create randoms numbers between 1 and a specified imax value.

我什至创建了自己的randint函数来解决该问题,尽管由于它用于大型数据集,因此在我的程序中无法高效运行:

I even created my own randint function to solve the problem although it doesn't run very efficiently in my program since it is used for large data sets:

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

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

Is there a built-in function to create a random integer that is either a 0 or 1 or is there a more efficient way to create such a function in MATLAB?

推荐答案

这似乎要快一些:

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

或者,如果您需要将结果作为double:

Or, if you need the result as double:

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

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

Examples with m = 100, n = 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中生成0或1的随机整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆