フィルターのクリア

generating random numbers only 2 numbers with percentage

6 ビュー (過去 30 日間)
Takim Mustakim
Takim Mustakim 2022 年 4 月 21 日
編集済み: Riccardo Scorretti 2022 年 4 月 21 日
how to generating random numbers 1x100 but only 2 numbers (suppose 0 and 1) with percentage 0=30% and 1=70%

回答 (1 件)

Riccardo Scorretti
Riccardo Scorretti 2022 年 4 月 21 日
編集済み: Riccardo Scorretti 2022 年 4 月 21 日
The function rand generates random numbers uniformely distributed between 0 and 1. Hence, it is enough to set to 1 numbers the value of which is higher than 0.30 = 1 - 0.70, and to 0 all the others.
n = 10000; % = number of values to generate
prob_1 = 0.70;
num = rand(n,1) > (1-prob_1);
num(num ~= 1) = 0;
% Validation
numel(find(num == 1)) / n
ans = 0.7009
numel(find(num == 0)) / n
ans = 0.2991

カテゴリ

Help Center および File ExchangeSources についてさらに検索

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by