How to tranform a vector into a matrix?

How to transform a vector of type:

[[1.021434087e-5, 1.532972083e-5, -1.493500137e-5], 
[-0.19951695340554, 0.87894179053067, -0.62713882127936], 
[0.76712229809243, 0.24863902907755, 0.74526241504934], 
[0.35580334399536, -0.82601803138729, -0.62993342769733], 
[-0.92343260142312, -0.30159515034176, 0.51179839372872]]

to a matrix

 1.021434087e-5    1.532972083e-5   -1.493500137e-5;
-0.19951695340554  0.87894179053067 -0.62713882127936;
 0.76712229809243  0.24863902907755  0.74526241504934;
 0.35580334399536 -0.82601803138729 -0.62993342769733;
-0.92343260142312 -0.30159515034176  0.51179839372872

Does this work for you @Leticia-maria ?

julia> vcat(A'...)
5×3 Matrix{Float64}:
  1.02143e-5   1.53297e-5  -1.4935e-5
 -0.199517     0.878942    -0.627139
  0.767122     0.248639     0.745262
  0.355803    -0.826018    -0.629933
 -0.923433    -0.301595     0.511798

The more performant and clean way is in a package:

julia> using SplitApplyCombine

# if you need an actual materialized matrix:
julia> @btime combinedims($A, 1)
  257.150 ns (2 allocations: 192 bytes)

# if a view of the original vector is fine:
julia> @btime combinedimsview($A, 1)
  3.165 ns (0 allocations: 0 bytes)

# for comparison:
julia> @btime mapreduce(permutedims, vcat, $A)
  390.875 ns (14 allocations: 1.03 KiB)
julia> @btime vcat($A'...)
  885.152 ns (24 allocations: 768 bytes)
1 Like

Very interesting. I have always liked the SAC package for the functions it provides and for the propensity for functional programming that I like so much.
could you explain specifically which functions / algorithms are used internally in SAC that make this transformation (conceptually relatively simple) much faster than the other proposals?

I don’t think SAC.jl does something special here. If you write a simple for-loop and allocate the whole resulting array upfront, performance will be the same. It’s the mapreduce(vcat) and vcat(A...) that are inefficient - the latter is fundamentally type-unstable.

As for combinedimsview, which is two orders of magnitude faster, it just doesn’t materialize the resulting array, providing a view instead.

1 Like