Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array Multiplication in Julia

I'm trying to do something that I believe should be relatively simple in Julia, but I can't seem to find any mention of this problem.

Basically what I've got is an mxn matrix, and an nx1 vector. What I would like to do is multiply the vector against the matrix, elementwise, but along the axis such that every element of the matrix is multiplied.

In numpy for instance this would be:

np.multiply(array, vector)

Is there any way to do this in Julia?

I tried just extending the vector to fill an array:

projection = 1:size(matrix)[1]
weight_change = hcat(map(x -> vector, projection))

but that yields something with a type of Array{Array{Float64, 2}, 2}, when what I really need is just Array{Float64, 2}, which means that an elementwise multiplication won't really work.

Is there any way to either fix my approach or remedy my bugged solution?

like image 882
Slater Victoroff Avatar asked Feb 12 '14 03:02

Slater Victoroff


Video Answer


1 Answers

You're looking for the .* element-wise, broadcasting multiply operator:

julia> A = [ i + j*im for i=1:3, j=1:4 ]
3x4 Array{Complex{Int64},2}:
 1+1im  1+2im  1+3im  1+4im
 2+1im  2+2im  2+3im  2+4im
 3+1im  3+2im  3+3im  3+4im

julia> v = [1:4]
4-element Array{Int64,1}:
 1
 2
 3
 4

julia> w = [1:3]
3-element Array{Int64,1}:
 1
 2
 3

julia> A .* w
3x4 Array{Complex{Int64},2}:
 1+1im  1+2im  1+3im   1+4im
 4+2im  4+4im  4+6im   4+8im
 9+3im  9+6im  9+9im  9+12im

julia> A .* v'
3x4 Array{Complex{Int64},2}:
 1+1im  2+4im  3+9im   4+16im
 2+1im  4+4im  6+9im   8+16im
 3+1im  6+4im  9+9im  12+16im
like image 162
StefanKarpinski Avatar answered Dec 11 '22 09:12

StefanKarpinski