# Refactoring a symmetric matrix into a vector and back again

Hallo,

Do you know ‘good’ ways to refactor a symmetric matrix into a vector, and back again?
Ideally, something like this:

A = [1 2 3; 2 4 5; 3 5 6]
V = mat2vec(A) # V = [1 2 3 4 5 6]
A = vec2mat(V) # A = [1 2 3; 2 4 5; 3 5 6]

Many thanks,

See

Maybe it’s not a “good” way in the sense you expect, but in some cases it could work

``````julia> function symmat2vec(m)
n=size(m,1)
N=n*(n+1)÷2
v=Vector{eltype(m)}(undef,N)
for idx in 1: N
j = Int(ceil(sqrt(2 * idx + 0.25) - 0.5))
i = Int(idx - (j-1) * (j) / 2)
v[idx] = m[i, j]
end
v
end
symmat2vec (generic function with 1 method)

julia> function vec2symat(v)
N=size(v,1)[1]
n=Int((-1+ sqrt(1+8*N))/2)
m=Matrix{eltype(v)}(undef,n,n)
rngs=[Int(n*(n-1)/2+1):Int(n*(n+1)/2) for n in 1:4]
for c in 1:4
r=4*(c-1)+1:4*(c-1)+4
m[r]= v[[rngs[c];getindex.(rngs[c+1:end],c)]]
end
m
end
vec2symat (generic function with 1 method)

julia> m=[ 11 2 13 4; 2 3 4 25; 13 4 5 6; 4 25 6 77]
4×4 Matrix{Int64}:
11   2  13   4
2   3   4  25
13   4   5   6
4  25   6  77

julia> v=symmat2vec(m)
10-element Vector{Int64}:
11
2
3
13
4
5
4
25
6
77

julia> vec2symat(v)
4×4 Matrix{Int64}:
11   2  13   4
2   3   4  25
13   4   5   6
4  25   6  77
``````