Reputation: 847
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
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
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
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