필터 지우기
필터 지우기

Random numbergeneration with constraints

조회 수: 5 (최근 30일)
Lusine
Lusine 2012년 7월 5일
Hi,
I want to generate a random matrix, with two constraints 1.the sum of each row of the matrix is less or equal to let's say 60. 2.And the values must be within a specified range, say between 10 and 20.
Can anyone help me with this?
Thank you so much for your help!

채택된 답변

Tom
Tom 2012년 7월 5일
ulim=20; %max value
llim=10; %min value
rowlim=60; %max sum for each row
m=5; %rows
n=4; %columns
RMat=rand(m,n)*(ulim-llim)+llim;
Rsum=sum(RMat,2);
Rcheck=Rsum>rowlim;
while any(Rcheck) %replace any row whose sum is > rowlim
I=find(Rcheck);
RMat(I,:)=rand(length(I),n)*(ulim-llim)+llim;
Rsum=sum(RMat,2);
Rcheck=Rsum>rowlim;
end
disp(RMat)
  댓글 수: 1
Lusine
Lusine 2012년 7월 7일
Thanks! It was a great help for me!

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

추가 답변 (2개)

Nirmal
Nirmal 2012년 7월 5일
What happens if number of columns is something large may be 20? it would definitely cross your constraint of 60. if you plot the histogram of random numbers every number are equally likely. if you set the number of columns to be within certain limit based on your limit on the sum you can achieve what you are looking for, otherwise the number you will generate will not be random.

Walter Roberson
Walter Roberson 2012년 7월 6일

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by