MATLAB: Random numbergeneration with constraints

constraintsrandom number generator

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!

Best Answer

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)