MATLAB: Generate n pairs of random integers, whose 0 <= pairwise_sum <= k

pairwise sumrandom number generatorsum

I want to generate n pairs of integers {(x_i, y_i)}, such that x_i + y_i <= k. One way I can think of is to generate one pair at a time
pairs = zeros(n,2)
for i=1:n
pairs(i,1) = randi(0,k);
pairs(i,2) = randi(0,k - pairs(i,1));
end
But, certainly, for loop is not favorable in matlab. Also, I'm not sure if that guarantees randomness either. I wonder if there's any existing function or a better way to do that?
Variation: consider a constraint that we want m% of generated pairs have pairwise_sum <= h ( h is some number < k). My approach won't work in this case. I'd love to get some hints to solve that as well.
Many thanks,

Best Answer

num_pairs = 100;
max_val = 10;
tot_sum = randi(max_val + 1,[num_pairs,1]) - 1; %Need to include 0
result = rand(num_pairs,2);
result = bsxfun(@rdivide,result, sum(result,2));
result = round(bsxfun(@times,result,tot_sum));
plot(result)
I don't understand your second constraint.