0 or 1のランダムな2D配列の生成

18 views (last 30 days)
osamu
osamu on 30 Jun 2023
Commented: Akira Agata on 3 Jul 2023
サイズがM×Nで値が0 or 1のランダムなの2次元配列の生成方法について教えてください。
0と1の数はおおよそ50%:50%(M,Nが奇数の場合を含むため)としたく、またM,Nは1000~2000の大きいサイズのためできるだけ計算量やメモリ消費量が少ない方法が望ましいです。
また他の環境でも使えるようにツールボックスは使わないで実装したいです。
宜しくお願いします。

Answers (1)

Atsushi Ueno
Atsushi Ueno on 30 Jun 2023
randi関数(整数の一様分布の疑似乱数)を使うのが良いと思います。
M = 2000; N = 2000;
data = randi(2,M,N)-1;
sum(data,'all')/(M*N) % 大体50%になった
ans = 0.4996
  1 Comment
Akira Agata
Akira Agata on 3 Jul 2023
+1
他にも以下のような方法もあります。
M = 2000; N = 2000;
% 方法1: randi関数で 0 or 1 を出力するよう指定する
data1 = randi([0, 1], M, N);
% 方法2: rand関数の出力が 0.5 以上かどうかで 0,1を決める
data2 = rand(N, M) > 0.5;
data2 = double(data2);
% 念のため 1 の出現確率を確認
r1 = sum(data1, 'all')/(N*M)
r1 = 0.5000
r2 = sum(data2, 'all')/(N*M)
r2 = 0.4998

Sign in to comment.

Categories

Find more on 乱数発生器 in Help Center and File Exchange

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!