防止 Julia 自动转换一维矩阵切片的类型 [英] Prevent Julia from automatically converting the type of a 1D matrix slice
问题描述
alpha = [1 2 3; 4 5 6]
alpha[:, 1] # Type is Array{Int64, 1}
alpha[:, 1:2] # Type is Array{In64, 2}
我只是想阻止自动类型转换,但我很难弄清楚如何做到这一点.是的,我可以直接使用 alpha[:, 1]''
,但我想防止内存重新分配.vec()
用于另一个方向(1xn 矩阵),但我找不到将 (nx1) 矩阵保持为矩阵的函数.
I just want to prevent the automatic type conversion, but I am having an amazingly hard time figuring out how to do this. Yeah, I could just go alpha[:, 1]''
, but I want to prevent the memory reallocation. There is vec()
for going the other direction (1xn matrix) but I can't find a function for keeping a (nx1) matrix a matrix.
推荐答案
使用长度为 1 的范围,而不仅仅是索引
不要简单地指定所需列的索引 (Int64
),而是指定 长度 1 的范围 (UnitRange{Int64}
): 1:1
.
Use a range of length 1 instead of just an index
Instead of simply specifying the index (Int64
) of the desired column, specify a range (UnitRange{Int64}
) of length 1: 1:1
.
这将诱使 Julia 保留二维数组类型 (Array{Int64,2}
),而不是返回向量 (Array{Int64,1}
).
That will trick Julia into preserving the 2D-array type (Array{Int64,2}
) instead of returning a vector (Array{Int64,1}
).
Edit: the developers discussed this topic here (thanks to Colin for pointing me to it).
julia> alpha = [1 2 3; 4 5 6]
2x3 Array{Int64,2}:
1 2 3
4 5 6
julia> alpha[:,1] # nope
2-element Array{Int64,1}:
1
4
julia> alpha[:,1:1] # yep
2x1 Array{Int64,2}:
1
4
这篇关于防止 Julia 自动转换一维矩阵切片的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!