2
votes

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?

1
Your example is unclear to me (perhaps you meant ndgrid(1:A(1), 1:A(2), 1:A(3))). Is this what you want, with vectors = arrayfun(@(x) {1:x}, A)?Luis Mendo
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

1 Answers

2
votes

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);