I’m constructing the Hessian of the Rosenbrock function. I want the return of h! to be of type Symmetric.
using LinearAlgebra
# for completeness
function f(x; a=1, b=100)
(a - x[1])^2 + b*(x[2] - x[1]^2)^2
end
function h!(H, x; a=1, b=100)
H[1, 1] = 2 + 8b*x[1]^2 - 4b*(x[2] - x[1]^2)
H[1, 2] = -4b*x[1]
#H[2, 1] = H[1, 2] I want to save this step
H[2, 2] = 2b
return H = copy(Symmetric(H))
end
Your function is returning a Symmetric matrix, it’s just not changing the type of H. As far as I know you can’t mutate something to a different type. Once you assign a type to something, it’s always going to be that type.
Yes, S = Symmetric(A) is a view of the parent A. And A can be reached with S.data. For completeness, S also contains a character, either 'u' or 'l' to tell if the view uses the upper or lower part of A. At the REPL, a quick way to check what’s in an object is to place a dot and hit TAB to autocomplete:
julia> H0 = Symmetric(rand(2,2))
2×2 Symmetric{Float64, Matrix{Float64}}:
0.422018 0.115722
0.115722 0.732627
julia> H0. # press TAB twice here with the cursor after the dot
data uplo
julia> H0.data # the non-symmetric parent
2×2 Matrix{Float64}:
0.422018 0.115722
0.0112565 0.732627
julia> H0.uplo # tells that we use the upper part of the parent, i.e., H0[1,2] == H0.parent[1,2]
'U': ASCII/Unicode U+0055 (category Lu: Letter, uppercase)