How to create static Matrix from a normal Matrix

I find this behaviour very confusing:

The following works, but I am certain that there must be better ways to do it:
SMatrix{size(tester)...}(tester)

How should I construct a static vector?

This is explicitly stated in the docs:

m5 = SMatrix{2,2}([1 3 ; 2 4]) # Array conversions must specify size

When you’re using a macro, the macro can only see the syntax. In the first case, it can figure out the size of the result, but in the second case it just sees a symbol and has no idea what hides behind it.

1 Like

Alright, that makes sense.

I have now defined the following in my script:

svec(x::AbstractVector) = SVector{length(x)}(x)
svec(some_vector) == SVector{length(some_vector)}(some_vector) # returns true

Why is that, and something like it, not defined? It seems awfully redundant to write the proposed

m5 = SMatrix{2,2}([1 3 ; 2 4])

, when the dimensions of [1 3; 2 4] can be found from the input.

In this case SMatrix{2,2}([1 3 ; 2 4]) the function SMatrix does not have access to the size at type level, the macro @SMatrix does. If you allow SMatrix(matrix) you will end up with a lot of users having type unstable code which would defeat a lot of the purpose of StaticArrays, speed and stack allocation. The function you defined is indeed type unstable for normal arrays.

3 Likes

Got it. Thanks!