Julia allows you to do that sort of thing even without copying any data:
julia> m = [i+j for i in 1:3, j in 1:4]
3×4 Matrix{Int64}:
2 3 4 5
3 4 5 6
4 5 6 7
julia> m1 = vec(m) # m1 points to the same memory address as m
12-element Vector{Int64}:
2
3
4
3
4
5
4
5
6
5
6
7
julia> m2 = reshape(m, 4, 3) # m2 still points to the same memory address as m
4×3 Matrix{Int64}:
2 4 6
3 5 5
4 4 6
3 5 7
If you are wondering what "points to the same memory address" means have a look at this example:
julia> m2[1,1] = -66
-66
julia> m
3×4 Matrix{Int64}:
-66 3 4 5
3 4 5 6
4 5 6 7
Finally, if at any point you actually need a copy rather than a reference to the same data use copy(m)
or as commented by @DNF m[:]
(this is a dimension drop operator that returns a Vector
with copy of data from any Array
).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…