If you know the number of factors in the product (for example, you will be multiplying 3 sets), then ndgrid
does everything for you:
A = [-1 -3 -5]
B = [10 11]
C = [0 1]
[X, Y, Z] = ndgrid(A, B, C)
P = [X(:) Y(:) Z(:)]
where the matrix P lists the elements of the products in the form you want.
For a variable number of factors, MATLAB approach does not seem to work (or I could not figure out how to pass a variable number of arguments to ndgrid
in Scilab). Instead, I looked up the source of ndgrid and followed its logic.
// input is a cell array of row vectors
c = cell()
n = // number of vectors
for k=1:n
c(k).entries = // your k-th vector
end
// Here the code that receives the cell array c and finds the product
n = length(c)
dim = zeros(1,n)
for k=1:n
dim(k) = length(c(k).entries)
end
P = zeros(prod(dim),n)
for k=1:n
f1 = ones(1,prod(dim(k+1:$)))
f2 = ones(1,prod(dim(1:k-1)))
P(:,k) = (f1.*.(c(k).entries).*.f2)'
end
Again, P has the elements of the product, one in each row. Note that .*.
is not a typo: it's the Kronecker product of vectors. For example,
[1 2 3].*.[1 1] = [1 1 2 2 3 3]
[1 1].*.[1 2 3] = [1 2 3 1 2 3]
Kronecker product with 1-vectors f1
and f2
ensures that the entries are repeated in the correct pattern to produce all product elements. Swapping f1
and f2
results in a different ordering of elements, which may be more to your liking.