Generating all ordered samples with replacement

4 ビュー (過去 30 日間)
Riccardo
Riccardo 2019 年 5 月 7 日
コメント済み: Jan 2019 年 5 月 8 日
Hello everybody,
is there a function in Matlab which generates an array containing all ordered samples of length k taken from a set of n elements , that is all the k-tuples where each can be any of the , and whose total number is ?
Or can anybody suggest a simple code to generate all of them? I am guessing it involves the iterative use of datasample function checking that every new generated sample is different from the previous ones, but I couldn't find so far a satisfactory way to write it

採用された回答

Jan
Jan 2019 年 5 月 7 日
編集済み: Jan 2019 年 5 月 7 日
If you do not have a C-compiler:
function Y = VChooseKRO_M(X, K)
X = X(:);
nX = numel(X);
Y = zeros(nX ^ K, K);
r1 = nX ^ (K - 1);
r2 = 1;
for k = 1:K
Y(:, k) = repmat(repelem(X, r1, 1), r2, 1);
r1 = r1 / nX;
r2 = r2 * nX;
end
end
  1 件のコメント
Riccardo
Riccardo 2019 年 5 月 7 日
Thanks a lot!

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

その他の回答 (2 件)

Guillaume
Guillaume 2019 年 5 月 7 日
編集済み: Guillaume 2019 年 5 月 7 日
For and ,
n = 20;
k = 5;
result = dec2base(0:n^k-1, n); %generate all n^k samples with replacement, as char vector 0-9 + A-Z
result = result - '0' + 1; %convert character to numbers 1-10, A-Z get converted to 18+
result(result>17) = result(result>17) - 7 %convert 18+ to 11+
For greater n you'll have to use Jan's answer.
  1 件のコメント
Riccardo
Riccardo 2019 年 5 月 7 日
Thanks to you too.

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


Riccardo
Riccardo 2019 年 5 月 8 日
What about this solution, I don't know if it's as fast as yours, but do you think is correct?
function Y = ordsampwithrep(X,K)
%ordsampwithrep Ordered samples with replacement
% Generates an array Y containing in its rows all ordered samples with
% replacement of length K with elements of vector X
X = X(:);
nX = length(X);
Y = zeros(nX^K,K);
Y(1,:) = datasample(X,K)';
k = 2;
while k < nX^K +1
temprow = datasample(X,K)';
%checknew = find (temprow == Y(1:k-1,:));
if not(ismember(temprow,Y(1:k-1,:),'rows'))
Y(k,:) = temprow;
k = k+1;
end
end
end
  3 件のコメント
Riccardo
Riccardo 2019 年 5 月 8 日
Thanks, I have tested with a script for and , and I agree, it's quite slower (around 14 seconds compared with 0.01-0.002 seconds). I just wanted to know if it's formally correct.
Jan
Jan 2019 年 5 月 8 日
Yes, it is formally correct.

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

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by