Is this the proper way of computing a simple forward difference algorithm in the x-direction in Julia, given h=1
on a 2D array/image?
function forward_diff_i(f)
∇ᵢ₊ = zeros(size(f))
for j in 1:size(f, 2), i in 1:size(f, 1) - 1
∇ᵢ₊[i, j] = f[i + 1, j] - f[i, j]
end
# Compute backward diff for edge case
for j in 1:size(f, 2)
∇ᵢ₊[end, j] = f[end, j] - f[end - 1, j]
end
return ∇ᵢ₊
end
If so, what's the recommended way to account for the edge?
have you looked at the diff
function in base Julia?
Oh no I hadn't actually. Looks like it's performing a similar operation and the results are similar on my end. Thanks
Here is what I have decided on, in case this is at all useful
function forward_diff_i(f)
∇ᵢ₊ = padarray(f, Pad(1, 1))
for j in 1:size(f, 2), i in 1:size(f, 1)
∇ᵢ₊[i, j] = ∇ᵢ₊[i + 1, j] - ∇ᵢ₊[i, j]
end
return parent(∇ᵢ₊[1:end-1, 1:end-1])
end
I'd consider renaming this topic to "forward differences" to not confuse it with forward mode automatic differentiation like implemented in ForwardDiff.jl
Done
Last updated: Dec 28 2024 at 04:38 UTC