Matrix of all possible combinations of some indices in Matlab

做~自己de王妃 提交于 2020-08-08 06:56:10

问题


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:

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


来源:https://stackoverflow.com/questions/62593020/matrix-of-all-possible-combinations-of-some-indices-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!