# Generic square matrix constructor from a vector?

**URL:** <https://discourse.julialang.org/t/generic-square-matrix-constructor-from-a-vector/62306>\
**Category:** General Usage\
**Tags:** constructors\
**Created:** [June 2, 2021, 10:16pm UTC](https://discourse.julialang.org/t/generic-square-matrix-constructor-from-a-vector/62306 "2021-06-02T22:16:29Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Vasily\_Pisarev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vasily_pisarev/32/7929_2.png) [@Vasily\_Pisarev](https://discourse.julialang.org/u/Vasily_Pisarev)\
**Post date:** [June 2, 2021, 10:16pm UTC](https://discourse.julialang.org/t/generic-square-matrix-constructor-from-a-vector/62306/1 "2021-06-02T22:16:29Z")

</div>

Is there a generic way, given a vector, to produce a square matrix of the “best matching” type? By “best matching” I mean here `Matrix` for `Base` vectors and views, `MMatrix` for static arrays and `SizedMatrix` for `SizedVector`s from StaticArrays.jl.

For arrays in `Base`, there’s of course `similar(vec, (length(vec), length(vec)))`. However, it does not produce the desired result with static vectors (returns an ordinary matrix for the sake of type stability).

I have come to the following:

```julia
function sqmatr(vec::AbstractVector{T}, F::DataType = T) where {T}
    cinds = CartesianIndices((eachindex(vec), eachindex(vec)))
    return similar(cinds, F)
end

```

which handles `Base.Vector` and `SVector`/`MVector` but not `SizedVector` (returns `MMatrix` when `SizedMatrix` would be desired).

The ideal option would be `similar(vec * vec')` but without the actual computation of the outer product.  
Is there a way to do that without introducing an explicit dependency on StaticArrays.jl?

---

<div class="post-metadata">

**Author:** ![Vasily\_Pisarev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vasily_pisarev/32/7929_2.png) [@Vasily\_Pisarev](https://discourse.julialang.org/u/Vasily_Pisarev)\
**Post date:** [July 21, 2021, 5:42am UTC](https://discourse.julialang.org/t/generic-square-matrix-constructor-from-a-vector/62306/2 "2021-07-21T05:42:24Z")

</div>

So, I eventually found the following solution:

```julia
function sqmatr(vec::AbstractVector{T}, F::DataType = T) where {T}
    axis, = axes(vec)
    return similar(vec, F, (axis, axis))
end

```
