필터 지우기
필터 지우기

How to Generate random number that most of them ZEROs

조회 수: 2 (최근 30일)
zeezo
zeezo 2018년 5월 22일
편집: dpb 2018년 5월 24일
Hi,
I would like to generate a set of 50 numbers that are in the range of [0-2] and follow uniformly distributed; however, I want most of them to be 0( Zeros).
I tried the following code but it does not generate most of them zeros.
N=randi([0 2],1,50)
Thank you
  댓글 수: 1
Akira Agata
Akira Agata 2018년 5월 23일
"range of [0-2] and follow uniformly distributed" but "most of them to be 0" ? It's not clear for me what the 50 random number array you want looks like. Please tell us more details on what you would like to generate?

댓글을 달려면 로그인하십시오.

채택된 답변

Jeff Miller
Jeff Miller 2018년 5월 23일
x=zeros(1,50);
r=rand(1,50);
PrZero = .8; % Adjust as needed to achieve "most of them zeros"
x(r<(1-PrZero)/2) = 1;
x(r>1-(1-PrZero)/2) = 2;
histogram(x);
  댓글 수: 1
zeezo
zeezo 2018년 5월 23일
편집: zeezo 2018년 5월 23일
Thank you very much. this is very helpful.
If I want to make a change to the range to be from 0 to 4 instead of 0 to 2, what should I do?

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

dpb
dpb 2018년 5월 23일
편집: dpb 2018년 5월 24일
Well, if they're to be uniformly distributed then only 33% of them on average will be zero; that's what "uniform" means.
You can generate an array of N zeros and then distribute some M other values within it, but you won't be able to call it "uniformly distributed"
To answer the follow-up as well...
S=50; % sample size
M=1; N=4; % range other than zeros
x=zeros(S,1); % initialize
k=round(S*(1-pz)); % pz ==> PrZero --> compute number nonzero
x(randperm(S,k))=randi([M N],1,k); % spread that many around
  댓글 수: 2
zeezo
zeezo 2018년 5월 23일
Thank you.
The code does not work it shows this error "Error using randperm K must be less than or equal to N."
dpb
dpb 2018년 5월 23일
Typo; I first had N as the sample size then changed it to S and missed the use in the argument to randperm
x(randperm(S,k))=...
made the correction in Answer...

댓글을 달려면 로그인하십시오.


Jeff Miller
Jeff Miller 2018년 5월 24일
It depends a little on whether you want (1) exactly the same number of zeros in each random set, or (2) a large number of zeros on average. I interpreted the question in the latter way (i.e., the number of zeros would fluctuate randomly). If that is indeed what you want, then it is probably easiest to do it like this:
S=50; % sample size
M=1; N=4; % range other than zeros
PrZero = .8; % Whatever proportion of zeros you want on average.
x=randi([M N],1,S); % Uniformly distributed random numbers from M to N
r=rand(1,S); % Random numbers from 0-1
x(r<PrZero) = 0; % Select out random positions in x and overwrite them with zero
histogram(x)

카테고리

Help CenterFile Exchange에서 Random Number Generation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by