Reshape a Matrix to a vector

I have a matrix X with dimensions (1000,4). I want to convert this matrix to a vector of vectors such that the size of the resulting vector is (1000,) where each element has the size (4,). I tried using reshape(X, (1000,)) but that does not work. Could you please help. Thanks!

Depending on what you want to do with the resulting vector of vectors it would be more idiomatic Julia to use eachrow to create an iterator over views of the rows.

help?> eachrow
search: eachrow searchsorted searchsortedlast searchsortedfirst

  eachrow(A::AbstractVecOrMat)

  Create a generator that iterates over the first dimension of vector or matrix A, returning the rows as AbstractVector
  views.

  See also eachcol, eachslice, mapslices.

  │ Julia 1.1
  │
  │  This function requires at least Julia 1.1.

  Example
  ≡≡≡≡≡≡≡≡≡

  julia> a = [1 2; 3 4]
  2×2 Matrix{Int64}:
   1  2
   3  4
  
  julia> first(eachrow(a))
  2-element view(::Matrix{Int64}, 1, :) with eltype Int64:
   1
   2
  
  julia> collect(eachrow(a))
  2-element Vector{SubArray{Int64, 1, Matrix{Int64}, Tuple{Int64, Base.Slice{Base.OneTo{Int64}}}, true}}:
   [1, 2]
   [3, 4]
1 Like

Dealing with lots of vectors of a small fixed size (e.g. 4) is often a sign that you might be better off using StaticArrays.

e.g.

julia> using StaticArrays

julia> A = rand(1000,4);

julia> V = [@SVector[A[i,1], A[i,2], A[i,3], A[i,4]] for i in axes(A,1)]
1000-element Vector{SVector{4, Float64}}:
 [0.4434452477917964, 0.3446253018597002, 0.5674041252593228, 0.7059583131641392]
 [0.19970405217542575, 0.9579823112299621, 0.8512050026856272, 0.09805315719974939]
 ⋮
 [0.15556234340431896, 0.4183665044671866, 0.7501469249778085, 0.5471984014874345]
 [0.3607016689564623, 0.3410541849909612, 0.7761437088965141, 0.5671709603611581]

The elements of V will be much quicker to work with than a Vector, and V is also stored more efficiently than an array of Vector. (The price is that you need to make sure that the length of the SVectors is known to the compiler, as I did above by simply hard-coding the length. If you have a wide variety of short lengths, then this requires more care, and it may not be worth it at all if the lengths of the short vectors changes frequently.)

2 Likes

Note also that since Julia is column major, a matix of size (4,1000) can be reinterpreted as 1000 static arrays of size 4, but a matrix of size (1000,4) can’t.

6 Likes