How to generate random number within a sum limit?

9 Ansichten (letzte 30 Tage)
Arnab Pal
Arnab Pal am 7 Nov. 2017
Beantwortet: Roger Stafford am 7 Nov. 2017
Generate 5 random numbers, where their sum should be less/equal to 50.

Akzeptierte Antwort

Birdman
Birdman am 7 Nov. 2017
while true
A=randi([1 15],5,1);
if(sum(A)<=50)
break;
end
end
disp(A)
disp(sum(A))
  2 Kommentare
Arnab Pal
Arnab Pal am 7 Nov. 2017
ok, it is working. But I need decimal number also. It is giving the only integer. Thank u
Birdman
Birdman am 7 Nov. 2017
Bearbeitet: Birdman am 7 Nov. 2017
while true
t=15;
A=t*rand(5,1);
if(sum(A)<=50)
break;
end
end
disp(A)
disp(sum(A))
You can change t.

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (1)

Roger Stafford
Roger Stafford am 7 Nov. 2017
If the numbers are supposed to be any five positive integers, do this:
b = true;
while b
x = 50*randi(5,1);
b = sum(x)>50;
end
If the numbers can be any non-negative real numbers, change the third line above to:
x = 50*rand(5,1);

Kategorien

Mehr zu Dates and Time finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by