英文:
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))')
Here is the matrix.
I've one method but it's 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?
英文:
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))')
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?
答案1
得分: 2
我会假设Point3
只是SVector{3, Float64}
的另一个名称。然后,你可以通过以下方式从矩阵的行创建一个向量:Point3.(eachrow(p_mat))
,代码如下:
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)) # 与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]
...
英文:
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]
...
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论