How to generate random numbers 0 and 1

I need to generate random numbers 0 and 1,if i use randi(1) it will be in fraction. exactly i need to generate 0 and 1 randomly???pls help

 採用された回答

Image Analyst
Image Analyst 2015 年 1 月 30 日
編集済み: Image Analyst 2015 年 1 月 30 日

8 投票

Try
n = 10; % However many numbers you want.
randomNumbers = randi([0, 1], [1, n])
This will give a double. If you want integers, then cast to int32.
randomNumbers = int32(randi([0, 1], [1, n]));
or use logical() if you want booleans.

その他の回答 (2 件)

Michael Haderlein
Michael Haderlein 2015 年 1 月 30 日

1 投票

e.g.
randi(2)-1
or
fix(rand*2)
Best regards,
Michael

3 件のコメント

shruthi m
shruthi m 2015 年 1 月 30 日
Thanku..if i need to generate random of n numbers of 0 and 1 ???
Michael Haderlein
Michael Haderlein 2015 年 1 月 30 日
randi(2,n,1)-1
or
fix(rand(n,1)*2)
Kamal yahya
Kamal yahya 2020 年 2 月 27 日
grid=fix(randi([0 1],100));
imtool(grid)

サインインしてコメントする。

Nawaf Alharbi
Nawaf Alharbi 2018 年 9 月 10 日

1 投票

r=randi(2,n,1)-1

カテゴリ

ヘルプ センター および File ExchangeCreating and Concatenating Matrices についてさらに検索

タグ

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by