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

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,

 採用された回答

José-Luis
José-Luis 2014 年 9 月 29 日
編集済み: José-Luis 2014 年 9 月 29 日

0 投票

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.

3 件のコメント

Khanh
Khanh 2014 年 9 月 29 日
Thank you so much, Jose. The use of bsxfun is so cool. Just want to make sure I understand it right, the last 2 lines are equivalent to the following, right?
result = result ./ sum(result,2);
result = round(result .* tot_sum)
For the constraint, for example with max_val = 10 in your example, what if I want to assure that 70% of the pairs generated have sum <= 7 (h = 7 in this case). How can I do that?
Thank you,
José-Luis
José-Luis 2014 年 9 月 29 日
編集済み: José-Luis 2014 年 9 月 29 日
Yes, it is equivalent, except that it applies it to both columns.
Two ways to do the second constraint pop to my mind:
  1. Generate 70 samples with that constraint and add 30 with one such that 7 < h < 10
  2. Trim the generated sample until you reach your condition (get rid of some of the rows)
Please accept the answer that best solves your problem.
Khanh
Khanh 2014 年 9 月 29 日
That makes sense. Thanks.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

ヘルプ センター および File ExchangeLoops and Conditional Statements についてさらに検索

質問済み:

2014 年 9 月 29 日

コメント済み:

2014 年 9 月 29 日

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by