问题
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:
A minor modification of this answer works. The required changes are:
- Define the vectors to be "combined" based on
A
. - 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);
来源:https://stackoverflow.com/questions/62593020/matrix-of-all-possible-combinations-of-some-indices-in-matlab