Matlab中某些索引的所有可能组合的矩阵 [英] Matrix of all possible combinations of some indices in Matlab
本文介绍了Matlab中某些索引的所有可能组合的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑大小为1xL
的Matlab向量A
,报告一些严格的正整数.我想构造一个尺寸为prod(A,2)xL
的矩阵T
,报告来自1:1:A(1)
,1:1:A(2)
,...,1:1:A(L)
的所有可能的L
元组.
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)
.
例如,取L=3
和A=[2 3 1]
.然后T
可以构造为
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(:)];
如何将以上代码概括为通用的L
?
How can I generalise the code above to a generic L
?
推荐答案
对此答案的较小修改.所需的更改是:
A minor modification of this answer works. The required changes are:
-
在载体中定义要组合"的载体.基于
- 在此处用
{:}
索引替换{end:-1:1}
索引,以相反的字典顺序获得结果.
A
.
- 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);
这篇关于Matlab中某些索引的所有可能组合的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文