matrixvectorcopyjuliavec

Language Julia: convert vector in matrix


Who can help.

To transform a vector into a one-dimensional matrix just run in Julia:

a = copy(permutedims([1,2,3]))

To transform the matrix "a" into a vector just use:

b = copy(vec(a))

If you have a matrix "[1 2 3; 4 5 6]" to transform it into a vector, just:

c = vec([1 2 3; 4 5 6])

Now how to make the vector have the form of the 2x3 matrix like:

2×3 Matrix{Int64}:
 1  2  3
 4  5  6

Solution

  • You can use reshape

    julia> c = vec([1 2 3; 4 5 6])
    6-element Vector{Int64}:
     1
     4
     2
     5
     3
     6
    
    julia> M=reshape(c,2,3)
    2×3 Matrix{Int64}:
     1  2  3
     4  5  6
    

    Note that this operation does not reallocate memory, c and M share the same memory. By example:

    julia> c[1]=10
    10
    
    julia> M
    2×3 Matrix{Int64}:
     10  2  3
      4  5  6