Reputation: 69
There is a downloadable function called CARTPROD which gives the cartesian product of given vectors (link to CARTPROD function)
For example
cartprod(1:3,1:3)
ans =
1 1
2 1
3 1
1 2
2 2
3 2
1 3
2 3
3 3
However, is there a way in which I can specify how many times a given vector should be read in the cartesian product. I want something like this:
%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)
I have tried thinking about it, but I can't think of doing it any way besides manually. Thanks!
Upvotes: 0
Views: 130
Reputation: 19689
The other answer points out how you can use the same cartprod
function from the FEX. However, there is another function named combvec
(from the Neural Network Toolbox) which does exactly the same.
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
Upvotes: 1
Reputation: 2059
What you're looking for is comma separated lists. Haven't tested this, but try
myvec={1:3,1:3,1:3,1:3};
cartprod(myvec{:}); %get cartprod of all vectors in the cell-array.
or as @Sardar_Usama pointed out, you can replace myvec={1:3,1:3,1:3,1:3}
with this:
n=4; %number of repeated vectors
myvec=repmat({1:3},1,n); %repeat cell-array {1:3} 4 times
Upvotes: 2