2

Is there an equivalent function for tuples in Matlab as there is for Mathematica?

See the first example:

http://reference.wolfram.com/language/ref/Tuples.html

I just mean the outputs and not necessarily the braces.

Thank you.

dsmalenb
  • 149
  • 8
  • Is [this](https://stackoverflow.com/q/21895335/2586922) what you want? It will give a matrix where each row is a tuple. For the first Mathematica example you would use input `clear vectors; vectors(1:3) = {[0 1]}` – Luis Mendo Nov 07 '17 at 22:53
  • I want to specify a set of inputs, say [1 2 5] and specify how many "buckets" I am interested in, say 2. Then I should get for this example: [1 1], [1 2], [1 5], [2 1], [2 2], [2 5], [5 1], [5 2], [5 5]. It is essentially every combination with repetition of any element. – dsmalenb Nov 07 '17 at 23:54
  • You can find the answer here: https://www.mathworks.com/matlabcentral/fileexchange/7147-permn-v--n--k- – dsmalenb Nov 08 '17 at 00:01

1 Answers1

0

As I stated in comments, you only need to adapt this answer. You can do it as follows:

function y = tuples(x, n)
y = cell(1,n);
[y{end:-1:1}] = ndgrid(x);
y = cat(n+1, y{:});
y = reshape(y, [], n);

This gives a matrix where each row is a tuple. For example:

>> tuples([1 2 5], 2)
ans =
     1     1
     1     2
     1     5
     2     1
     2     2
     2     5
     5     1
     5     2
     5     5
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147