Reputation: 4062
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
Upvotes: 10
Views: 10973
Reputation: 6086
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
Upvotes: 15
Reputation: 4062
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.
Upvotes: 0