Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random matrix of Integers with fixed row sums in Julia

I would like to create a random matrix with the following constraints:

  • all values should be Integer values
  • fixed row sums (decreasing with row e.g. 100, 50, 10, 5 etc.)
  • random values from 0 to 6

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!

like image 954
Anaj Avatar asked Oct 18 '25 08:10

Anaj


1 Answers

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
like image 97
Bogumił Kamiński Avatar answered Oct 19 '25 23:10

Bogumił Kamiński