MATLAB: How to generate matrices that satisfies constraints on sum of row elements and sum of column elements

constrained matrix generation

An example to clarify what I mean:
Generate some 2×3 matrices such that:
1) sum of row elements: row_sum=[100; 200; 300]
2) sum of column elements: column_sum=[500 100]
3) All elements greater than or equal to zero.
Possible_matrix_1=[100 0;200 0;200 100]
Possible_matrix_2=[50 50; 200 0;250 50]
and so on…
I understand that one way to is to generate random matrices and eliminate the ones that don't satisfy the conditions. However, I'd prefer something more efficient if it is possible.
Thank you
Kind regards,
Sharadhi

Best Answer

New code with speficied target row and col sum, using FEX randfixesum and requires optimization toolbox
EDIT: new code no longer requires FEX
rs = [100; 200; 300] % target row sum
cs = [500, 100] % target column sum
if abs(sum(rs)-sum(cs)) > 1e-10*abs(sum(rs))
error('sum(rs) must be equal to sum(cs)');
end
% This part need to be done once if rs and cs are unchanged
m = length(rs);
n = length(cs);
I = zeros(m,n);
I(:) = 1:m*n;
Aeq = accumarray([repmat((1:m)',n,1) I(:); repelem(m+(1:n)',m,1) I(:)],1);
beq = [rs(:); cs(:)];
lb = zeros(m*n,1);
ub = inf(m*n,1);
B = zeros(m*n);
for k=1:m*n
f = accumarray(k, 1, [m*n 1]);
B(:,k) = linprog(f, [], [], Aeq, beq, lb, ub);
end
% This part generate new random A
x=-log(rand(m*n,1)); x=x./sum(x);
% x = randfixedsum(m*n,1,1,0,1); % Fex
A = reshape(B*x,[m n])
% Check
sum(A,2) % ~ rs
sum(A,1) % ~ cs