Suppose I have 4 letters and I want to arrange them in 3 places (repetition allowed), so I would have 43=64 possible permutations. How can I compute and print them?
Asked
Active
Viewed 2.0k times
8
-
possible duplicate of [Matlab - Generate all possible combinations of the elements of some vectors](http://stackoverflow.com/questions/4165859/matlab-generate-all-possible-combinations-of-the-elements-of-some-vectors) – Eitan T Sep 03 '13 at 12:29
-
This is actually the cartesian product and is quite different from the concept of permutations. – knedlsepp Feb 02 '15 at 23:44
-
function `perms('abcd')` returns all non-repeating permutations; it gets very slow as the input vector grows in size – Girardi Oct 14 '16 at 19:07
4 Answers
9
Simplifying Amro's answer, you could use this:
%// Sample data
x = 'ABCD'; %// Set of possible letters
K = 3; %// Length of each permutation
%// Create all possible permutations (with repetition) of letters stored in x
C = cell(K, 1); %// Preallocate a cell array
[C{:}] = ndgrid(x); %// Create K grids of values
y = cellfun(@(x){x(:)}, C); %// Convert grids to column vectors
y = [y{:}]; %// Obtain all permutations
Matrix y
should store the permutations you're after.
3
An intuitive one-liner:
unique(nchoosek(repmat('ABCD', 1,4), 3), 'rows')
Although nice-looking, it's slow and inefficient. Don't use it for large data sets.

Rody Oldenhuis
- 37,726
- 7
- 50
- 96
-
Nice try. While this will work for Matlab, GNU/Octave (versión 4.0.0) can't interpret it, cause `nchoosek` can only accept numeric vectors. – nightcod3r Oct 22 '18 at 08:21
1
Pseudocode solution:
Generate the (base ten) numbers 0 to 63.
Change them to base 4, which only has the digits 0, 1, 2, and 3.
Convert numbers to letters.
The actual Matlab code is left as an exercise for the student.

dmm
- 495
- 5
- 12