2

Consider a Matlab vector A of size 1xL, reporting some strictly positive integers. I want to construct a matrix T of size prod(A,2)xL reporting all the possible L-tuples from 1:1:A(1), 1:1:A(2), ..., 1:1:A(L).

For example, take L=3 and A=[2 3 1]. Then T can be constructed as

[ca, cb, cc] = ndgrid(1:1:A(1), 1:1:A(2), 1:1:A(3));
T= [ca(:), cb(:), cc(:)]; 

How can I generalise the code above to a generic L?

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
TEX
  • 2,249
  • 20
  • 43
  • 1
    Your example is unclear to me (perhaps you meant `ndgrid(1:A(1), 1:A(2), 1:A(3))`). Is [this](https://stackoverflow.com/q/21895335/2586922) what you want, with `vectors = arrayfun(@(x) {1:x}, A)`? – Luis Mendo Jun 26 '20 at 10:56
  • Thanks. 1- Yes, that is what I meant. 2- I want almost that, except that the final ordering of the elements does not follow exactly what `ngrid` gives. I checked `combs` obtained with that code and my `T` and I got different matrices. – TEX Jun 26 '20 at 11:05

1 Answers1

2

A minor modification of this answer works. The required changes are:

  1. Define the vectors to be "combined" based on A.
  2. Replace {end:-1:1} indexing there by {:} indexing here, to get the results in reverse lexicographical order.
A = [2 3 1];
vectors = arrayfun(@(x) {1:x}, A); % 1. Define input vectors from A
n = numel(vectors);
T = cell(1,n);
[T{:}] = ndgrid(vectors{:}); % 2. Results will be in reverse lexicographical order 
T = cat(n+1, T{:});
T = reshape(T,[],n); 
Luis Mendo
  • 110,752
  • 13
  • 76
  • 147