It always works out this way. Someone asks question A, when they really wanted question B answered. :)
You REALLY want to sample from a set in 9 dimensions, such that the sum of squares of the 9 numbers is 0.4. You could have said that in the first place! Grumble. :)
This is the one case where a sample and normalize scheme can work and be efficient, as long as you sample properly. What you need to recognize is that the sum of squares is equivalent to requiring the points lie on the surface of a 9 dimensional hypersphere.
Why does that help? Because you can use a rotationally symmetric distribution to solve the problem, and then normalize the result.
You did not say if the numbers may be positive or negative, or if all must be positive. That actually is irrelevant, as it turns out. We will sample using randn, which produces iid gaussian samples in any number of dimensions. It is completely valid to rescale them.
n = 10000;
targetsum = 0.4;
x = randn(n,9);
x = sqrt(targetsum)*x./sqrt(sum(x.^2,2));
min(sum(x.^2,2))
ans =
0.4
max(sum(x.^2,2))
ans =
0.4
The resulting samples will be uniformly distributed on the surface of the desired 9-dimensional hypersphere.
Now, if your problem requires that x be all positive, the symmetry of the unit normal distribution in n-dimensions saves you. Just take the absolute value of x.
It would NOT have been valid to re-scale a sample taken using rand though. That would NOT be at all a uniform sampling, failing for the same essential reason I showed above. Of course, it is difficult to plot in 9 dimensions to prove it. Ok. Just trust me here.
But, please, please, please don't ask me how to generate samples such that the sum of cubes is a constant.