Search code examples
matrixjulia

What is the difference between these two types of vectors of vectors (Julia)


I can define a "matrix" as a vector of vectors. i.e

vecMat = [[0,1],[1,2]]

If you run this in a jupyter notebook, this object is labeled as 2-element Vector{Vector{Int64}}.

Now if I did: newVecMat = eachcol(reduce(hcat,vecMat))

that type of object is labeled as 2-element ColumnSlices{Matrix{Int64}, Tuple{Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Base.Slice{Base.OneTo{Int64}}, Int64}, true}}

What is the difference between these two? Is there anything I should be aware about (perhaps mistmatching types somehow)?

edit: fixed typo in definition of vecMat


Solution

  • Tip: next time describe the actual problem you want solve, not only your method of solution (see XY problem). It helps to address the problem. And also, you may use unsuitable tools.

    In few words, Slice-objects are wrappers of arrays (vectors, matrices, etc) that helps to iterate through the array in a specific way. E.g. eachcol(M::Matrix) may be interpreted as an iterator over columns of matrix M.

    Slice-objects are memory-effective. For example, eachcol(M) does not copy elements of matrix M, but stores views to columns of M.

    julia> @allocated M = [1 2; 1 2]
    96
    
    julia> M
    2×2 Matrix{Int64}:
     1  2
     1  2
    
    julia> @allocated VV = [[1, 1], [2, 2]]  # columns of M as vector of vectors
    224
    
    julia> VV
    2-element Vector{Vector{Int64}}:
     [1, 1]
     [2, 2]
    
    julia> @allocated EC = eachcol(M)  # also columns of M
    32
    
    julia> EC
    2-element ColumnSlices{Matrix{Int64}, Tuple{Base.OneTo{Int64}}, SubArray{Int64, 1, Matrix{Int64}, Tuple{Base.Slice{Base.OneTo{Int64}}, Int64}, true}}:
     [1, 1]
     [2, 2]
    
    julia> EC == VV
    true
    

    As of awareness, some methods for Arrays (Vector, Matrix, ...) may not be implemented for slices in standard library. Though both slices and Arrays are subtypes of AbstractArrays.