MATLAB: Enumeration of all possible samples with replacement trough base conversion

baseconversionMATLABorderedreplacementsampling

Hello everybody,
I would like to write a fast efficient code to enumerate all possible samples with replacement. That is, I need a bijective function between the set of all samples of length k taken from a set of n elements and the subset of natural numbers fast to compute in Matlab.
I can identify every member of A as a number between 0 and so that I can consider every element of as a representation in base n, and I would like to convert it in base using the
base2dec('strn',n)
built-in function of Matlab. The problem I have is the one to convert row vectors containing elements of in strings that could be managed by base2dec.
Indeed, suppose I have generated all the samples with function
X = 0:1:(n-1)
M = VChooseKRO_M_2(X,k)
I would like then to use num2str function to convert every row of M to a string, but for example what I get is
str = num2str(M(8,:))
str = '0 0 0 0 2 1'
while I would like to obtain
str= '000021'
so that then
base2dec(str,3)
ans = 7
is the correct answer.
Could anybody help me or point to a better solution?

Best Answer

Hi Riccardo,
Converting to strings seems inefficient to me (and it not required for this problem either).
Here is an alternative way to get the output:
% I assume all elements in the vector are b/w '0' and 'n-1' inclusive.
N=5;
vec = [1 4 3 1] % In base 5, this is 241.
% now for the solution.
powN = (length(vec)-1): -1: 0; % output: powN = 3 2 1 0 (powers of N for each digit)
powN = N.^powN; % output: powN = 125 25 5 1 (place value of each digit for base 5)
ans = vec*(powN'); % output: ans = 241
Explanation: Generate powers of N in a vector and then dot multiply this to get your answer.
You can combine these statements if you wish to speed up your code. Try:
ans = vec*(N.^((length(vec)-1:-1:0)'));
Hope it Helps!