How to generate random number within a sum limit?

 채택된 답변

Birdman
Birdman 2017년 11월 7일

0 개 추천

while true
A=randi([1 15],5,1);
if(sum(A)<=50)
break;
end
end
disp(A)
disp(sum(A))

댓글 수: 2

ok, it is working. But I need decimal number also. It is giving the only integer. Thank u
Birdman
Birdman 2017년 11월 7일
편집: Birdman 2017년 11월 7일
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.

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

추가 답변 (1개)

Roger Stafford
Roger Stafford 2017년 11월 7일

0 개 추천

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);

카테고리

도움말 센터File Exchange에서 Random Number Generation에 대해 자세히 알아보기

질문:

2017년 11월 7일

답변:

2017년 11월 7일

Community Treasure Hunt

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

Start Hunting!

Translated by