ten
ten

Reputation: 817

How to vectorize more than one vector in Julia?

I want to write vectorized style code in Julia in the context of wanting to define a function which takes more than one vector as arguments like below.

[code]

using PyPlot;
m=[453 21 90;34 1 44;13 553 66]
a = [1,2,3]
b=[1,2,3]
f(x,y) = m[x,y]
f.(a,b)

#= expected result
3×3 Matrix{Int64}:
 453   21  90
  34    1  44
  13  553  66
#

[real result]

3-element Vector{Int64}:
 453
   1
  66

The dot notation only picks the first element of each row, ignoring the others, and makes a vector with just 3 elements instead of 3 x 3 matrix.

How can I write to get the expected result?

Any information would be appreciated.

Upvotes: 1

Views: 331

Answers (2)

pfitzseb
pfitzseb

Reputation: 2554

You're looking for

julia> f.(a, b')
3×3 Matrix{Int64}:
 453   21  90
  34    1  44
  13  553  66

Note the relevant section in the documentation for broadcast (type ?broadcast into a REPL session to access it):

Singleton and missing dimensions are expanded to match the extents of the other arguments by virtually repeating the value.

a is treated as a 3x1 matrix (but has the type Vector{T}), while b' is used as a 1x3 matrix (with the type Adjoint(T, Vector{T})). These are broadcast to the resulting 3x3 matrix.

When using a and b directly, no expansion of dimensions is necessary, and you'll end up with a 3x1 matrix.

Upvotes: 2

MarcMush
MarcMush

Reputation: 1488

one of the two vectors needs to be a row vector so that Julia understands what you want to do, this simple example should help you understand Julia broadcasting:

julia> [1,2,3] .+ [10,20,30] # both have the same dimensions
3-element Vector{Int64}:
 11
 22
 33

julia> [1,2,3]' .+ [10,20,30] 
# first has dimensions (1,3) and second (3,1) => result is dimension (3,3)
3×3 Matrix{Int64}:
 11  12  13
 21  22  23
 31  32  33

Upvotes: 2

Related Questions