Creating two random matrices
1 view (last 30 days)
Show older comments
Hi. I have 2 matrices. M1(4,6) and M2(4,2). The generation of the two matrices is random. Attached you can find an explanation of the constraints. How can I formulate that with an ILP? Thanks
4 Comments
Accepted Answer
James Tursa
on 8 Nov 2016
Edited: James Tursa
on 8 Nov 2016
E.g.,
% random matrix
M = rand(4,8);
% normalize per the 4-element sums
M(:,1:4) = bsxfun(@rdivide,M(:,1:4),sum(M(:,1:4),2));
M(:,5:8) = bsxfun(@rdivide,M(:,5:8),sum(M(:,5:8),2));
% scale per the desired sum
M(1:2,1:4) = M(1:2,1:4) * 0.50 * 2000;
M(1:2,5:8) = M(1:2,5:8) * 0.50 * 2000;
M(3:4,1:4) = M(3:4,1:4) * 0.70 * 2000;
M(3:4,5:8) = M(3:4,5:8) * 0.30 * 2000;
% divy up the results
M1 = M(:,[1:3 5:7]);
M2 = M(:,[4 8]);
EDIT: For required integer entries, you can use this ad-hoc modification (not quite exactly uniform since the fractional parts always go into M2, but maybe close enough for your purposes)
% random matrix
M = rand(4,8);
% normalize per the 4-element sums
M(:,1:4) = bsxfun(@rdivide,M(:,1:4),sum(M(:,1:4),2));
M(:,5:8) = bsxfun(@rdivide,M(:,5:8),sum(M(:,5:8),2));
% scale per the desired sum
M(1:2,1:4) = M(1:2,1:4) * 0.50 * 2000;
M(1:2,5:8) = M(1:2,5:8) * 0.50 * 2000;
M(3:4,1:4) = M(3:4,1:4) * 0.70 * 2000;
M(3:4,5:8) = M(3:4,5:8) * 0.30 * 2000;
% Adjust values to integers
F = floor(M);
D = M - F;
F(:,4) = F(:,4) + round(sum(D(:,1:4),2));
F(:,8) = F(:,8) + round(sum(D(:,5:8),2));
% divy up the results
M1 = F(:,[1:3 5:7]);
M2 = F(:,[4 8]);
0 Comments
More Answers (1)
Image Analyst
on 8 Nov 2016
Try Roger Stafford's utility: http://www.mathworks.com/matlabcentral/fileexchange/9700-random-vectors-with-fixed-sum
0 Comments
See Also
Categories
Find more on Random Number Generation in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!