Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cartesian product of two vectors in Julia

I have two vectors x and y, of respective lengths n and p. Is there a built-in way to create a np x 2 matrix which would be

x[1] y[1]
x[1] y[2]
...
x[1] y[p]
x[2] y[1]
...
x[n] y[p]

I can do that with a nested for loop, but I'm looking for a built-in function, if it exists.

like image 435
P. Camilleri Avatar asked Mar 30 '15 13:03

P. Camilleri


People also ask

How do you get the dot product in Julia?

We should have dot(x::RowVector, y::RowVector) = dot(transpose(x), transpose(y)) (see mailing list). Mathematically, an inner product on a vector space induces an... But if we define dot(a,b) = a'*b one would expect to get back a matrix (the outer product) when a and b are row vectors.

How do you use vector in Julia?

A Vector in Julia can be created with the use of a pre-defined keyword Vector() or by simply writing Vector elements within square brackets([]). There are different ways of creating Vector. vector_name = [value1, value2, value3,..] or vector_name = Vector{Datatype}([value1, value2, value3,..])

How do you write a matrix to Julia?

Julia provides a very simple notation to create matrices. A matrix can be created using the following notation: A = [1 2 3; 4 5 6]. Spaces separate entries in a row and semicolons separate rows. We can also get the size of a matrix using size(A).


1 Answers

At least in Julia 1.3, there is a built-in function Iterators.product, so Iterators.product(a, b) |> collect should do the trick.

like image 113
Matěj Račinský Avatar answered Sep 20 '22 11:09

Matěj Račinský