Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to subtract vector from matrix in Julia

Tags:

julia

What is the best way to subtract a vector of length N from a matrix of size (N, K) in Julia?

Of course, for loop or repmat should work but they do not seem to be the most efficient.

Can I use broadcast somehow?

like image 537
sholi Avatar asked Jun 06 '17 14:06

sholi


Video Answer


1 Answers

julia> [1 2 3; 4 5 6; 7 8 9] .- [1; 2; 3]
3×3 Array{Int64,2}:
 0  1  2
 2  3  4
 4  5  6

(obviously, subtracting horizontal vectors is also broadcasted)

julia> [1 2 3; 4 5 6; 7 8 9] .- [1 2 3]
3×3 Array{Int64,2}:
 0  0  0
 3  3  3
 6  6  6

Also, note that the broadcasted call .- in the top example is essentially equivalent to

julia> (-).([1 2 3; 4 5 6; 7 8 9], [1; 2; 3])
3×3 Array{Int64,2}:
 0  1  2
 2  3  4
 4  5  6

as of julia 0.6, unifying the f.(args) syntax / under-the-hood implementation for broadcasting functions with that for broadcasting operators.
(i.e. .- is no longer a separately defined operator, which happens to be a 'broadcasted' version of - ).

like image 101
Tasos Papastylianou Avatar answered Oct 03 '22 04:10

Tasos Papastylianou