Randomize matrix elements between two values, keeping fixed sums of rows and columns (MATLAB)

I have a bit of a technical problem, but I feel that this should be possible with the powerful MATLAB toolkit.

I have a random n by n matrix of 0 and w, e.g. generated using

A=w*(rand(n,n)<p);

The typical value of w will be 3000, but this should not matter much.

Now this matrix has two important quantities: vectors

c = sum(A,1); 
r = sum(A,2)';

These are two row vectors, the first is the sum of each column, and the second is the sum of each row.

What I want to do next is to randomize each value of w, for example, from 0.5 to 2. This I would do as

rand_M = (0.5-2).*rand(n,n) + 0.5
A_rand = rand_M.*A;

: , , c r. , , ,

A_rand_c = sum(A_rand,1);
A_rand_r = sum(A_rand,2)';

j = 1:n, A_rand_c(j) = c(j) A_rand_r(j) = r(j).

, , - rand_M - , , , , .

, , , . : A_rand_c(j) [(1-e)*c(j),(1+e)*c(j)] A_rand_r(j) of [(1-e)*r(j),(1+e)*r(j)]. e , , 0,001 - .

- ? , , . , , , , n = 50.

, A_rand, .

: , , , , while, . , : A_rand(i,j), , A_rand_c(j) A_rand_r(i) , . , , . , , . , , , , . , .

+4
1

, / A A_rand. A(2,5) = w , A_rand(2,5) = w. ?

/ , .

:

  • A_rand=zeros(size(A)) - ,
  • entries_left = A>0 - , , A_rand
  • col_totals=sum(A,1) - , A_rand
  • row_totals=sum(A,2) - , A_rand


while sum( entries_left(:) ) > 0

% STEP 1:
% function to fill entries in A_rand if entries_left has rows/cols with one nonzero entry
% you will need to keep looping over this function until nothing changes
% update() A_rand, entries_left, row_totals, col_totals every time you loop

% STEP 2:
% let (i,j) be the indeces of the next non-zero entry in entries_left
% assign a random number to A_rand(i,j) <= col_totals(j) and <= row_totals(i)
% update() A_rand, entries_left, row_totals, col_totals

end

update()
    A_rand(i,j) = random_value;
    entries_left(i,j) = 0;
    col_totals(j) = col_totals(j) - random_value;
    row_totals(i) = row_totals(i) - random_value;
end

random_value . , , - , N*w*p, p - , A ( /).

, n^2 . 200-200, 20 .

+1

All Articles