PokeLu
PokeLu

Reputation: 847

How can I efficiently turn a vector of 1-dim array into a 2-dim array(matrix) in Julia?

As mentioned I have a vector of 1D matrice, such as:

P_predefined = [[.3 .4 .2 .1], [.2 .3 .5 0.], [.1 0. .8 .1], [.4 0. 0. .6]]

I would like to turn it into a matrix of 2D, I tried to use vcat, for which I expected to behave like vstack in Python, but it doesn't work.

vcat(algorithm.predefinedP)

It still returns a vector

[[0.3 0.4 0.2 0.1], [0.2 0.3 0.5 0.0], [0.1 0.0 0.8 0.1], [0.4 0.0 0.0 0.6]] #Vector{Matrix{Float64}}

How should I do it in the right way?

Upvotes: 2

Views: 158

Answers (3)

AboAmmar
AboAmmar

Reputation: 5559

Since you mention efficiency, a comprehension will be 2X faster than vcat.

m, n = length(P_predefined), length(P_predefined[1])   
@btime mat = [$P_predefined[i][j] for i=1:$m, j=1:$n]
@btime mat = reduce(vcat, $P_predefined)

  # 29.347 ns (1 allocation: 192 bytes)
  # 72.131 ns (1 allocation: 192 bytes)

Upvotes: 1

Eric Hanson
Eric Hanson

Reputation: 86

Julia 1.9 has stack, which can be used on earlier Julia versions via the package Compat.

julia> using Compat

julia> P_predefined = vec.([[.3 .4 .2 .1], [.2 .3 .5 0.], [.1 0. .8 .1], [.4 0. 0. .6]])
4-element Vector{Vector{Float64}}:
 [0.3, 0.4, 0.2, 0.1]
 [0.2, 0.3, 0.5, 0.0]
 [0.1, 0.0, 0.8, 0.1]
 [0.4, 0.0, 0.0, 0.6]

julia> stack(P_predefined)
4×4 Matrix{Float64}:
 0.3  0.2  0.1  0.4
 0.4  0.3  0.0  0.0
 0.2  0.5  0.8  0.0
 0.1  0.0  0.1  0.6

julia> stack(P_predefined; dims=1)
4×4 Matrix{Float64}:
 0.3  0.4  0.2  0.1
 0.2  0.3  0.5  0.0
 0.1  0.0  0.8  0.1
 0.4  0.0  0.0  0.6

Note: your P_predefined is a vector of 1xn matrices, instead of vectors. I've used vec here to convert them to vectors.

Upvotes: 7

phipsgabler
phipsgabler

Reputation: 20950

vcat(A...)

Concatenate along dimension 1. To efficiently concatenate a large vector of arrays, use reduce(vcat, x).

julia> reduce(vcat, P_predefined)
4×4 Matrix{Float64}:
 0.3  0.4  0.2  0.1
 0.2  0.3  0.5  0.0
 0.1  0.0  0.8  0.1
 0.4  0.0  0.0  0.6

Upvotes: 3

Related Questions