2

I've been looking for a fucntion that is building Cartesian product of given sets, just like this:

Example: A = [-1 -3 -5]; B = [10 11]; C = [0 1]; 

X = SETPROD(A,B,C) 
X = 

  -5 10 0 
  -3 10 0 
  -1 10 0 
  -5 11 0 
  -3 11 0 
  -1 11 0 
  -5 10 1 
  -3 10 1 
  -1 10 1 
  -5 11 1 
  -3 11 1 
  -1 11 1

Actually I was able to find such function for Matlab http://www.mathworks.com/matlabcentral/fileexchange/5898-setprod but unfortunately that doesn't work in Scilab.

I know this problem is pretty straightforward, but this is my first program that I'm doing in Scilab. Thank you!

kvat314
  • 23
  • 3
  • 2
    This MATLAB post may help you. You may be able to transfer it over using SciLab: http://stackoverflow.com/questions/21895335/generate-a-matrix-containing-all-combinations-of-elements-taken-from-n-vectors – rayryeng Nov 30 '14 at 19:21
  • Scilab has an `ndgrid` function, so that should work. – David Nov 30 '14 at 21:47

1 Answers1

0

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.

Community
  • 1
  • 1