Hi Everyone,
I want to create a matrix based on 1000 random samples of 50 numbers selected from 1 to 100, as follows:
a = [];
for i =1:n
y = randsample(100,50);
a = horzcat(a,sort(y));
end
Here the variable "a" should have 1000 fields for 50 random numbers selected from 1 to 100
I want to make sure that the numbers are unique for each field. Does anyone know the best way to do this?
Thanks

回答 (2 件)

Jan
Jan 2017 年 8 月 14 日
編集済み: Jan 2017 年 8 月 21 日

0 投票

a = zeros(n, 50);
for i =1:n
a(i, :) = sort(randsample(100,50));
end
[EDITED] Or do you mean that the rows should be guaranteed to be different? Then:
% Rejection method:
a = zeros(n, 50);
i = 0;
while i < n
v = sort(randperm(100, 50));
if ~any(all(a(1:i, :) == v, 2))
i = i + 1;
a(i, :) = v;
end
end

3 件のコメント

Steve Sous
Steve Sous 2017 年 8 月 14 日
Thank you for your reply!
I might have misinterpreted what I need. The code you wrote still invokes the randample function separately 1000 times. Does that guaranty that the 1000 random samples (50 each) from a(i=1:1000,:) are unique?
Thank you
José-Luis
José-Luis 2017 年 8 月 15 日
Yes.
Jan
Jan 2017 年 8 月 20 日
編集済み: Jan 2017 年 8 月 21 日
See [EDITED]

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

Akira Agata
Akira Agata 2017 年 8 月 17 日

0 投票

Just in case, you can check the uniqueness by:
% Make a variable 'a'
a = zeros(1000, 50);
for i =1:1000
a(i, :) = sort(randsample(100,50));
end
% Check the uniqueness
isUnique = true(1000,1);
for i =1:1000
if length(unique(a(i,:))) ~= 50
isUnique(i) = false;
end
end
any(~isUnique)

2 件のコメント

Steve Sous
Steve Sous 2017 年 8 月 21 日
I think I might be missing something! The suggested code does not give nonunique values. For example, if I add the following code line in the middle:
a(10,:) = a(1,:);
Which forces a replicate, the any(~isUnique) is still 0
Here is the full code
% Make a variable 'a'
a = zeros(1000, 50);
for i =1:1000
a(i, :) = sort(randsample(100,50));
end
%Added Line
a(10,:) = a(1,:);
% Check the uniqueness
isUnique = true(1000,1);
for i =1:1000
if length(unique(a(i,:))) ~= 50
isUnique(i) = false;
end
end
any(~isUnique)
Akira Agata
Akira Agata 2017 年 8 月 22 日
Well, I don't understand your point clearly.
In my previous code, each row of a contains unique 50 random number. That means length(unique(a(k,:))) is always 50 for all k (=1:1000). Therefore, even if you add the line "a(10,:) = a(1,:);", the output any(~isUnique) becomes 0 and there is no strange point in this behavior.
So, I would be happy if you could explain clearly what is the point and what kind of output you want to obtain.

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

カテゴリ

タグ

質問済み:

2017 年 8 月 14 日

コメント済み:

2017 年 8 月 22 日

Community Treasure Hunt

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

Start Hunting!

Translated by