By using Ref()
, it protects the object inside it from being iterated over. Supoose we define the following function fun
. See the examples below that demonstrate how broadcasting works:
fun(a,x)=a.-x
Case 1:
fun.([1,2], [3,4])
Note that without Ref()
, both arguments of function fun
are interated over from broadcasting. This implies that each element within each argument will be computed element-wise. ([1-3, 2-4])
2-element Vector{Int64}:
-2
-2
Case 2:
fun.([1,2], Ref([3,4]))
Note that Ref()
protects [3,4]. Therefore only [1,2] are iterated over, not [3,4]. This means that 1 is repeated over 3 and 4, resulting in 1-3, 1-4 respectively. Then 2 is repeated over 3 and 4, resulting in 2-3, 2-4. As a result, the final output will appear as follows:
2-element Vector{Vector{Int64}}:
[-2, -3]
[-1, -2]
Case 3:
fun.(Ref([1,2]), [3,4])
This case, only [3,4] are iterated over, not [1,2]. This means that 3 is repeated over 1 and 2, resulting in 1-3, 2-3 respectively. Then 4 is repeated over 1 and 2, resulting in 1-4, 2-4, respectively. As a result, the final output will appear as follows:
2-element Vector{Vector{Int64}}:
[-2, -1]
[-3, -2]
Reference
https://freecontent.manning.com/vectorizing-your-code-using-broadcasting/