Returns all n^k variations when picking k elements from an n-element vector (while allowing to pick the same element repeatedly).
Felix Bie?mann (2021). Variations: pick k elements out of n (https://www.mathworks.com/matlabcentral/fileexchange/19200-variations-pick-k-elements-out-of-n), MATLAB Central File Exchange. Retrieved .
The recursive approach is nice, and indeed KFROMN has additional value over NCHOOSEK. However, there are other algorithms that are much faster. See, for instance, my own COMBN submission.
tic ; t = combn(1:8,7) ; toc
% Elapsed time is 1.753454 seconds.
tic ; t2 = kfromn(1:8,7) ; toc
% Elapsed time is 8.253503 seconds.
Actually useful. This function allows k > n. nchoosek does not.
Not needed. Already in MATLAB, e.g., nchoosek
C = nchoosek(n,k) where n and k are nonnegative integers, returns n!/((nk)! k!). This is the number of combinations of n things taken k at a time.
C = nchoosek(v,k), where v is a row vector of length n, creates a matrix whose rows consist of all possible combinations of the n elements of v taken k at a time. Matrix C contains n!/((nk)! k!) rows and k columns.
Find the treasures in MATLAB Central and discover how the community can help you!Start Hunting!