I would like to create a random matrix with the following constraints:
I tried to create a random matrix and scale it to my fixed row sums I want, but then I get the problem that I get Float values (rounding does not help either)
A = rand(0:6, 5, 10)
sum_vec = [10,5,3,2,2]
for i = 1:length(A[:,1])
# row sum
s = sum(A[i,:])
A[i,:] = (A[i,:] /s ) * sum_vec[i]
end
Thanks a lot for your help!
You have not said what distribution your random numbers should follow, so I have made some arbitrary choice.
Here is an example function you can use to generate what you want, where n
is the number of elements that have to be integers from 0 to 6, and s
is their desired sum:
function fixed_sum_sample(n, s)
s > 6*n || s < 0 && throw(ArgumentError("wrong arguments"))
x = zeros(Int, n)
options = Set(1:n)
for _ in 1:s
i = rand(options) # you might want something else than uniform sampling
x[i] += 1
x[i] == 6 && pop!(options, i)
end
return x
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With