How to convert a vector into matrix in Julia

In Julia's ecosystem, the inbuilt reshape function allows converting a vector into a matrix. Typically, this function returns an array having the same data as the specified array but with different dimensions.

Syntax

The syntax of the reshape function is given below.

reshape(input_array, output_dims)

It accepts the following parameters:

  • input_array: The array to be processed

  • output_dims: The specified dimension

The output dimensions, output_dims, can be specified either as a list of arguments or as a shape tuple. One dimension can be specified with a : and its length is calculated so that its product with all the specified dimensions corresponds to the original array's input_array length.

Let's look into the following examples showing how to perform such a conversion:

Example

This example shows how to convert a vector into a 1-D matrix:

v = [10,20,30,40,50]
print("input vector:",v)
print("\noutput matrix:",reshape(v,(:,1)))

Explanation

  • Line 1: Defines a vector and stores it in a variable called v.

  • Line 2: Prints out an informative message showing the specified vector.

  • Line 3: Converts the vector into a 1-D matrix and print out the output generated.

Example

This example illustrates how to transform a vector into a 2-D matrix:

v = [0:9;]
print("input vector:",v)
print("\noutput matrix:",reshape(v,(2,5)))

Explanation

  • Line 1: Defines a vector of integer values ranging from 0 to 9 and stores it in a variable called v.

  • Line 2: Prints out an informative message showing the specified vector.

  • Line 3: Converts the vector into a 2-D matrix while specifying as dimensions (2,5), which means 2 dimensions of 5 elements each, and prints out the output generated.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved