Thanks for your patience with such a simple question, but I’m stumped. In a function, I want to:
- Declare a vector of vectors
- Iterate through two loops and update the original vector of vectors
- Return the vector of vectors
For some reason, the output of my function is set correctly throughout the loop, but then after the loop ends, these changes aren’t in scope. I don’t understand this next part either - for some reason, the 1st and 2nd row of the output are equal in the output of the function, but they were set to be different (as shown in the print statements in the code below).
How can I fix this scope issue?
Code:
using StaticArrays
using ComponentArrays
import LinearAlgebra: norm
r̅₁ = [0.0, 0.0, 0.0]
v̅₁ = [0.0, 0.0, 0.0]
m₁ = 5.972167867791379e24
r̅₂ = [0.0, 11681000.0, 0.0]
v̅₂ = [5134.0, 4226.0, 2787.0]
m₂ = 150.0
B = SVector{2}([ComponentArray((r̅=r̅₁, v̅=v̅₁)), ComponentArray((r̅=r̅₂, v̅=v̅₂))])
p = ComponentArray((G=6.6743e-11, m=[m₁, m₂]))
function gradient(B, p)
local ∂B = SVector{length(B)}(fill(ComponentArray((r̅=[0.0, 0.0, 0.0], v̅=[0.0, 0.0, 0.0])), size(B)))
for i = 1:length(B)
∂B[i].r̅ = B[i].v̅
for j = 1:length(B)
if i ≠ j
∂B[i].v̅ += ((p.m[i] * p.m[j]) / norm(B[j].r̅ .- B[i].r̅)^3 * (B[j].r̅ .- B[i].r̅))
end
end
∂B[i].v̅ *= (p.G / p.m[i])
println("∂B[", i, "] = ", ∂B[i])
end
println("∂B = ", ∂B)
end
gradient(B,p)
Output:
∂B[1] = (r̅ = [0.0, 0.0, 0.0], v̅ = [0.0, 7.337311123941769e-23, 0.0])
∂B[2] = (r̅ = [5134.0, 4226.0, 2787.0], v̅ = [0.0, -2.921310248692885, 0.0])
∂B = [(r̅ = [5134.0, 4226.0, 2787.0], v̅ = [0.0, -2.921310248692885, 0.0]), (r̅ = [5134.0, 4226.0, 2787.0], v̅ = [0.0, -2.921310248692885, 0.0])]