Reputation: 4828
I'm trying to grok Julia's dot vectorization syntax with a very simple example of a linear interpolating spline.
function createlookup(xk)
min_i = 1
max_i = size(xk, 1) - 1
function inner(x)
max(min(searchsorted(xk, x).stop, max_i), min_i)
end
inner
end
function linear_dydx(x, y)
diff(y, dims=1) ./ diff(x, dims=1)
end
function linear(xₖ, yₖ)
segment = createlookup(xₖ)
dydxₖ = linear_dydx(xₖ, yₖ)
function inner(x)
i = segment(x)
y = yₖ[i] + dydxₖ[i] * (x - xₖ[i])
end
inner
end
function main()
xₖ = [0.0, 1.0, 2.0, 4.0]
yₖ = [0.0, 2.0, 10.0, 13.0]
interpolator = linear(xₖ, yₖ)
x = [i/2.0 for i=0:10]
println(interpolator(2.43))
println(interpolator.(x))
end
main()
How deep in the call chain do I need to use the dot notation to make sure my main()
call to interpolator.(x)
is fully vectorized by the interpreter?
createlookup
need any vectorization?linear_dydx
already vectorized via diff
and ./
?@.
in front of y = yₖ[i] + dydxₖ[i] * (x - xₖ[i])
?I find myself throwing dots everywhere and nowhere and am not quite sure how to check whether I'm capturing everything while still preserving the broadcasting flexibility that dot notation is supposed to preserve.
Upvotes: 2
Views: 172
Reputation: 6378
The general strategy to keep in mind is to write all your functions as scalar functions if that makes sense. Once you've written your scalar operations, you can then apply them to the array by using .
once.
Upvotes: 3