Search code examples
matrixvectorjuliavectorization

How to convert a mxn matrix into a vector with same rows?


I'm trying to convert a Matrix into SVector in Julia. Following is a sample of how to create a matrix

p=randn(Point3,100)
p_mat=collect(reshape(reduce(vcat,p),3,length(p))')

enter image description here Here is the matrix. enter image description here

I've one method but its not very optimal.

[SVector{size(p_mat,2), Real}(p_mat[i,:]) for i in 1:size(p_mat,1)]

I'm trying to avoid the for loop and convert matrix into SVector. Is there another possible way?


Solution

  • I will assume Point3 is just another name for SVector{3, Float64}. Then, you can create a Vector from the matrix rows by Point3.(eachrow(p_mat)) as follows:

    using StaticArrays
    const Point3 = SVector{3, Float64}
    
    p = randn(Point3, 100)
    100-element Vector{SVector{3, Float64}}:
     [-0.643411054127986, -1.3146948793707078, 0.8560043466425089]
     [-1.2014944236615475, -0.16332265198198045, 0.7899287791641353]
     [-0.4468974734632806, -2.115137061106782, 1.2797367438232168]
     ...
    
    p_mat = [v[i] for v in p, i in 1:3]
    100×3 Matrix{Float64}:
     -0.643411   -1.31469     0.856004
     -1.20149    -0.163323    0.789929
     -0.446897   -2.11514     1.27974
     ...
    
    p_vec = Point3.(eachrow(p_mat)) # the same as p
    100-element Vector{SVector{3, Float64}}:
     [-0.643411054127986, -1.3146948793707078, 0.8560043466425089]
     [-1.2014944236615475, -0.16332265198198045, 0.7899287791641353]
     [-0.4468974734632806, -2.115137061106782, 1.2797367438232168]
     ...