How to generate random number in MATLAB

1 view (last 30 days)
Moe
Moe on 22 Mar 2020
Edited: dpb on 22 Mar 2020
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)

Answers (1)

Cris LaPierre
Cris LaPierre on 22 Mar 2020
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

Categories

Find more on Random Number Generation in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!