笛卡尔积的未定义长度Matlab

问题描述 投票:0回答:2

有一个名为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)

我已经尝试过考虑它,但除了手动之外,我想不出任何方式。谢谢!

matlab cartesian-product
2个回答
2
投票

你要找的是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

1
投票

另一个答案指出如何使用FEX中相同的cartprod函数。但是,还有另一个名为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
© www.soinside.com 2019 - 2024. All rights reserved.