function ind = word2ind(n,w)

% n is an integer
% w is a row vector where each element is between 1 and n, representing a
% word on the alphabet {1,...,n}
% Outputs index of the word w in the list of all possible words on
% {1,...,n}.

l = length(w);

assert(all(w >= 1) && all(w <= n),'Elements of w should be between 1 and n');

if l == 0
    ind = 1;
elseif l == 1
    ind = w+1;
else
    % Number of words of length strictly smaller than l = 1+n+n^2 + ... + n^(l-1) = (n^l - 1) / (n-1);
    i0 = (n^l - 1)/(n-1);
    % Because sub2ind needs a list of parameters (instead of a vector giving the indices)
    % we will convert w to a cell array
    w = num2cell(w);
    ind = i0 + sub2ind(n*ones(1,l),w{:});
end