Choose random element of vector
162 ビュー (過去 30 日間)
古いコメントを表示
I have a vector and i want to choose 2 random elements x1 and x2.
The x2 element I do not want to be the same element as x1 and i want to select after element x1
For example:
vector = [1,2,3,4,5,6,7,8,9]
element x1 may be the number 2. element x2 cannot be number 1 or number 2.
0 件のコメント
回答 (5 件)
Sindar
2020 年 1 月 24 日
編集済み: Sindar
2020 年 1 月 24 日
% select a random integer between 1 and the last index of the vector
ind_1 = randi([1 length(vector)]);
% select a random integer between ind_1 and the last index of the vector
ind_2 = randi([ind_1+1 length(vector)]);
% select the elements associated with these indices
x1=vector(ind_1);
x2=vector(ind_2);
1 件のコメント
Walter Roberson
2020 年 1 月 24 日
If length(vector) is randomly choosen for ind_1 then ind_2 has no room to be chosen from.
Walter Roberson
2020 年 1 月 24 日
P1 = randi(length(Vector) - 1);
P2 = randi([P1+1,length(Vector)]) ;
x1 = Vector(P1) ;
x2 = Vector(P2) ;
Note that this is not a fair distribution. You could get a fairer distribution if you dropped the requirement that x2 be chosen strictly after choosing x1:
P = sort(randperm(length(Vector, 2)));
x1 = Vector(P(1));
x2 = Vector(P(2));
This is fairer but violates the condition that x1 be chosen before x2.
0 件のコメント
James Tursa
2020 年 1 月 24 日
編集済み: James Tursa
2020 年 1 月 24 日
k = sort(randperm(numel(vector),2));
x1 = vector(k(1));
x2 = vector(k(2));
This assumes that you always want to be able to pick two numbers. I.e., x1 cannot be vector(end) and x2 cannot be vector(1).
0 件のコメント
giorgos kivides
2020 年 1 月 24 日
2 件のコメント
James Tursa
2020 年 1 月 24 日
To reverse order:
vector(k(1)+1:k(2)-1) = vector(k(2)-1:-1:k(1)+1);
To have random order:
m = randperm(k(2)-k(1)-1) + k(1) ;
vector(k(1)+1:k(2)-1) = vector(m);
参考
カテゴリ
Help Center および File Exchange で Creating and Concatenating Matrices についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!