How to generate random number in MATLAB

3 ビュー (過去 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

Community Treasure Hunt

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

Start Hunting!

Translated by