0 or 1のランダムな2D配列の生成
6 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
サイズがM×Nで値が0 or 1のランダムなの2次元配列の生成方法について教えてください。
0と1の数はおおよそ50%:50%(M,Nが奇数の場合を含むため)としたく、またM,Nは1000~2000の大きいサイズのためできるだけ計算量やメモリ消費量が少ない方法が望ましいです。
また他の環境でも使えるようにツールボックスは使わないで実装したいです。
宜しくお願いします。
0 commentaires
Réponses (1)
Atsushi Ueno
le 30 Juin 2023
randi関数(整数の一様分布の疑似乱数)を使うのが良いと思います。
M = 2000; N = 2000;
data = randi(2,M,N)-1;
sum(data,'all')/(M*N) % 大体50%になった
1 commentaire
Akira Agata
le 3 Juil 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)
r2 = sum(data2, 'all')/(N*M)
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!