Generate a matrix containing all combinations of elements from n vectors (Cartesian product)

The ndgrid function almost gives the answer, but has one caveat: n output variables must be explicitly defined to call it. Since n is arbitrary, the best way is to use a comma-separated list (generated from a cell array with ncells) to serve as output. The resulting n matrices are then concatenated into the desired … Read more

Why does application of `sequence` on List of Lists lead to computation of its Cartesian Product?

This works because using lists as monads in Haskell makes them model indeterminism. Consider: sequence [[1,2],[3,4]] By definition this is the same as: do x <- [1,2] y <- [3,4] return [x,y] Just read it as “First a choice between 1 and 2, then a choice between 3 and 4”. The list monad will now … Read more

Avoiding nested for loops

Here’s how to use product: x1 = range(min1, max1, step1) x2 = range(min2, max2, step2) x3 = range(min3, max3, step3) … for v1, v2, v3, v4, v5, v6 in itertools.product(x1, x2, x3, x4, x5, x6): do_something_with(v1, v2, v3, v4, v5, v6) or a bit more compactly: ranges = [ range(min1, max1, step1), range(min2, max2, step2), … Read more

Generate all possible combinations for Columns(cross join or Cartesian product)

in post-pandemic new world we can solve this with: =INDEX(FLATTEN(A2:A3&” “&TRANSPOSE(B2:B4))) to account for future expansion we can do: =INDEX(FLATTEN(FILTER(A2:A; A2:A<>””)&” “&TRANSPOSE(FILTER(B2:B; B2:B<>””)))) for 3 columns: =INDEX(FLATTEN(FLATTEN( FILTER(A2:A; A2:A<>””)&” “&TRANSPOSE( FILTER(B2:B; B2:B<>””)))&” “&TRANSPOSE( FILTER(C2:C; C2:C<>””)))) 4 columns: =INDEX(FLATTEN(FLATTEN(FLATTEN( FILTER(A2:A; A2:A<>””)&” “&TRANSPOSE( FILTER(B2:B; B2:B<>””)))&” “&TRANSPOSE( FILTER(C2:C; C2:C<>””)))&” “&TRANSPOSE( FILTER(D2:D; D2:D<>””)))) for more see: https://stackoverflow.com/a/74160711/5632629

How can I get “permutations with repetitions/replacement” from a list (Cartesian product of a list with itself)?

You are looking for the Cartesian Product. In mathematics, a Cartesian product (or product set) is the direct product of two sets. In your case, this would be {1, 2, 3, 4, 5, 6} x {1, 2, 3, 4, 5, 6}. itertools can help you there: import itertools x = [1, 2, 3, 4, 5, … Read more

tech