未定义长度的笛卡尔积Matlab

Cartesian product of undefined length Matlab

有一个名为 CARTPROD 的可下载函数,它给出给定向量的笛卡尔积 (link to CARTPROD function)

例如

cartprod(1:3,1:3)

ans =
 1     1
 2     1
 3     1
 1     2
 2     2
 3     2
 1     3
 2     3
 3     3

但是,有没有一种方法可以指定在笛卡尔积中应读取给定向量的次数。我想要这样的东西:

%If user chooses the vector to be used 4 times
cartprod(1:3,1:3,1:3, 1:3)

%If user chooses the vector to be used 2 times
cartprod(1:3,1:3)

我试过想过,但我想不出除了手动之外还有什么办法。谢谢!

您要找的是comma separated lists。尚未对此进行测试,但请尝试

myvec={1:3,1:3,1:3,1:3}; 
cartprod(myvec{:}); %get cartprod of all vectors in the cell-array.

或如@Sardar_Usama 指出的那样,您可以将 myvec={1:3,1:3,1:3,1:3} 替换为:

n=4; %number of repeated vectors
myvec=repmat({1:3},1,n); %repeat cell-array {1:3} 4 times

另一个答案指出了如何使用完全相同的 cartprod function from the FEX. However, there is another function named combvec(来自神经网络工具箱)。

n = 4;  %Number of times to be repeated
myvec = repmat({1:3},1,n);    %Repeating the cell array vector
result = combvec(myvec{:}).'; %Converting to comma-separated list and applying combvec