arraysjuliavectorizationvector-multiplication

Vectorized multiplication: Multiply two vectors in Julia, element-wise


I decided to dive into Julia and hitting the wall; fast.

I am trying to replicate a simple operation, which would like as follows in python numpy

a = numpy.array([1,2,3])
b = numpy.array([1,2,3])
a*b
[output]: [1,4,9]

In other words "[1,4,9]" is the output I expect.

I tried in Julia the following:

a = [1,2,3]
b = [1,2,3]
a*b
[output]: MethodError: no method matching *(::Array{Int64,1}, ::Array{Int64,1})

or after trying to wise up:

a = [1,2,3]
b = [1,2,3]'
a*b
[output]: 3×3 Array{Int64,2}:
 1  2  3
 2  4  6
 3  6  9

I am aware that this seems like a basic question, but my Googling does not seem my finest today and/or stackoverflow could use this question & answer ;)

Thanks for any help and pointers!

Best


Solution

  • Julia needs a . in front of the operator or function call to indicate you want elementwise multiplication and not an operation on the vector as a unit. This is called broadcasting the array:

     julia> a = [1,2,3]          
     3-element Array{Int64,1}:   
     1                          
     2                          
     3                          
    
     julia> b = [1,2,3]          
     3-element Array{Int64,1}:   
     1                          
     2                          
     3                          
    
     julia> a .* b               
     3-element Array{Int64,1}:   
     1                          
     4                          
     9