
Re: Generate random numbers with fixed sum and different constraints
Posted:
Nov 18, 2012 1:46 PM


I have not fully tested, but it should go like this:
% lower + upper bounds lo = [1 0 2 1 0]; up = [5 6 4 4 2]; % target sum s = 15; % number of samples n = 1000;
m = length(lo); slo = sum(lo); sup = sum(up);
x0 = interp1([slo; sup], [lo; up], s); if any(isnan(x0)) error('no solution exists') end
x0 = x0(:); B = null(ones(size(lo))); A = [B; B]; b = [x0lo(:); up(:)x0];
% FEX: http://www.mathworks.com/matlabcentral/fileexchange/30892 % Thank you Matt [V,nr,nre] = lcon2vert(A,b,[],[],tol);
T = delaunayn(V); P = V(T,:); P = reshape(P, [size(T) m1]); P = permute(P, [3 2 1]); np = size(P,3);
% http://www.mathworks.com/matlabcentral/fileexchange/9700 % % Thank you Roger Q = bsxfun(@minus, P, P(:,end,:)); Q(:,end,:) = []; vol = arrayfun(@(k) det(Q(:,:,k)), 1:np); vol = abs(vol); w = randfixedsum(m,n,1,0,1);
% generate n samples of v with probability vol vol = vol / sum(vol); c = cumsum(vol); c(end)=1; [~, i] = histc(rand(1,n),[0 c]);
V = P(:,:,i); y = zeros(m1, n); for k=1:n y(:,k) = V(:,:,k)*w(:,k); end x = bsxfun(@plus, x0, B*y);
% Bruno

