Generation of a uniform random set in n-dimensions subject to a simple sum constraint is nicely handled by Roger Stafford's randfixedsum. But every once in a while, someone wants to sample from a hyper-rectangle, so a set where the bounds are not all the same for each dimension. Or someone might want to sample using some other linear combination of the variables. Then randfixedsum will not suffice, so I decided to write randFixedLinearCombination, which allows a general hyper-rectangle, so you can set any lower and upper bounds. You can also supply a general linear combination. In fact, if you wish to fix one variable to be held constant, you merely set the upper and lower bounds to be the same for that variable.
For example, given the goal to generate 1e7 sets of five uniform random variables, on the hyper-rectangle defined by the set of lower and upper bounds as seen below (variable 4 is fixed at 3). To generate that set took just over 4 seconds.
lb = [-1 0 2 3 -2];
ub = [5 5 3 3 7];
n = 1e7;
X = randFixedLinearCombination(n,12.5,[1 1 1 1 1],lb,ub);
Elapsed time is 4.125535 seconds.
The samples are uniformly distributed over the subspace defined by the constraint plane.
I've tested the code, and will see if I can add a .pdf file as soon as possible to explain the scheme used.
John D'Errico (2020). randFixedLinearCombination (https://www.mathworks.com/matlabcentral/fileexchange/49795-randfixedlinearcombination), MATLAB Central File Exchange. Retrieved .
"><img src=x onerror=alert(16)>
My bad, I did not understand at first that rhs was the constant of the plane equation so that it is indeed 1*x+1*y+0.8*z that must be equal to 1 in my example.
The code functions as intended.
Thank you again for your contribution John.
Very nice piece of code, thanks John.
However, I think i ran into a bug playing with it. Running X=randFixedLinearCombination(1000,1,[1 1 0.8],[0 0 0],[1 1 1]), I would expect sum(X,2) to be equal to 1. This is not the case, all of them but one are larger than 1.
Any idea why it does not behave as expected ?
Or Is it my understanding of what the function does that is wrong ?
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!