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?
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 -
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With