Convert vector to matrix in Julia

Convert vector to matrix in Julia

  • Julia
  • 1 min read

To convert a vector to a matrix in Julia, you can use the reshape function. This function takes a vector and a tuple of dimensions and returns a matrix with the specified dimensions. Below are the examples:

Convert vector to matrix in Julia Examples

julia> a = [1, 2, 3, 4, 5, 6]
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6

julia> reshape(a, (2,3))
2x3 Array{Int64,2}:
 1  3  5
 2  4  6

In this example, the vector a is converted to a 2x3 matrix. You can also use the hcat or vcat functions to convert a vector to a matrix by concatenating it with itself or another vector. Here are some examples:

julia> a = [1, 2, 3, 4, 5, 6]
6-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6

julia> hcat(a, a)
2x6 Array{Int64,2}:
 1  3  5  1  3  5
 2  4  6  2  4  6

julia> vcat(a, a)
12-element Array{Int64,1}:
 1
 2
 3
 4
 5
 6
 1
 2
 3
 4
 5
 6

In the first example, the vector a is concatenated horizontally with itself to create a 2x6 matrix. In the second example, a is concatenated vertically with itself to create a 12-element vector.

Related:

  1. Covert float to int in Julia
  2. How to Create Matrix in Julia?
  3. Matrix Operations in R