Is there any way to convert an array into a matrix in place?
Thank you.
A matrix is a type of array. Do you mean convert a 1d array (a “vector”) into a 2d array (a “matrix”)? Use reshape
:
julia> v = [0:24;]
25-element Vector{Int64}:
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
julia> reshape(v, 5,5)
5Ă—5 Matrix{Int64}:
0 5 10 15 20
1 6 11 16 21
2 7 12 17 22
3 8 13 18 23
4 9 14 19 24
To complete the answer of stevengj, a Matrix{T}
is nothing else than an alias for Array{T,2}
, as Vector{T}
is nothing else than an alias for Array{T,1}
Thank you, but I noticed that using reshape function in a multi threading for loop eats too much memory.
Are there in place alternatives?
reshape
is in-place:
julia> v = rand(10^6);
julia> using BenchmarkTools
julia> @btime reshape($v, 1000,1000);
42.719 ns (2 allocations: 96 bytes)
Notice that the allocation here is quite small and is essentially just a wrapper object.
You can actually use an explicit wrapper object of type Base.ReshapedArray
with some undocumented internals:
julia> reshape2(v, dims) = Base.__reshape((v,IndexLinear()), (1000,1000))
reshape2 (generic function with 1 method)
julia> v = rand(10^6);
julia> @btime reshape2($v, (1000,1000));
2.034 ns (0 allocations: 0 bytes)
(Beware that the above reshape2
function doesn’t do any argument checking, e.g. it doesn’t check whether the sizes are compatible.)
See also the discussion in reshape(::Array, ...) is slow and allocates · Issue #36313 · JuliaLang/julia · GitHub
A safer version (with basically the same performance, but doing argument checking) should be:
reshape2(a, dims) = invoke(Base._reshape, Tuple{AbstractArray,typeof(dims)}, a, dims)
Does this work?
reshape(view(v, :), 1000, 1000)
Inserting the “view” first seems to avoid all heap allocations.