How to generate random number in MATLAB

조회 수: 1 (최근 30일)
Moe
Moe 2020년 3월 22일
편집: dpb 2020년 3월 22일
Hi everyone,
I'm trying to generate four random numbers in the MATLAB. I want some ["sum" intended methinks? --dpb] of these four numbers be equal to 100. Also, in total I want 1000 records generated with these conditions.
For example, consider following conditions for each of four targeted numbers:
Condition 1: greater than 10
Condition 2: between 0 and 90
Condition 3: less than 10
Condition 4: less than 10
Some examples as results:
Record 1: 15 ; 75 ; 5 ; 5 (total = 100)
Record 2: 10 ; 80 ; 5 ; 5 (total = 100)
Record 3: 40 ; 50 ; 8 ; 2 (total = 100)

답변 (1개)

Cris LaPierre
Cris LaPierre 2020년 3월 22일
So not truly random, since the values are co-dependent. There is nothing built-in that will do this, so you have to code the logic up yourself. Here's one way you could do it.
for r = 1:100
C1(r,1) = randi([10,100],1); % between 10 and 100
C3(r,1) = randi([0,min(10,100-C1(r))],1); % between 0 and 10
C4(r,1) = randi([0,min(10,100-C1(r)-C3(r))],1); % between 0 and 10
end
C2 = 100 - C1-C3-C4; % Between 0 and 90, but not random since the value is determined from the other 3 values

카테고리

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