10

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

dmeu
  • 3,842
  • 5
  • 27
  • 43

2 Answers2

14

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                          
Bill
  • 5,600
  • 15
  • 27
  • Oh wow, thanks. I had that dot/point at some point, since I have seen it. But I did not understand the meaning ;) Thanks! – dmeu Jul 13 '19 at 17:22
  • @Bill does this also work with different data types? I have `coeffs = repeat([0, 15, 30, 60], outer = states)` and `fs_t = fill(x -> (x)^0.6, nvar)` both of them would have same length. When I try to do `fs = fs_t .* coeffs` it throws up error saying `no method matching *(::var"#13#14", ::Int64)` What is the correct way to go about this? I'm basically constructing a list of different components of a objective function I want to use later on. –  May 02 '23 at 05:29
0

I just found a solution, although surely not optimal as it will generate a dot product and then select the diagonals.... to much calc!\

use LinearAlgebra
a = [1,2,3]
b = [1,2,3]
c = a * b'
diag(c)

I am pretty sure that there is a better solution.

dmeu
  • 3,842
  • 5
  • 27
  • 43