Conversion of the matrix to vector by row

Method 1: Using c() function

Simply passing the name of the matrix will do the job.

Syntax:

c(matrix_name)

Where matrix_name is the name of the input matrix

Example 1:

R




# create a matrix with 12 elements
# with 4 rows and 3 columns
matrix=matrix(1:12,nrow=4,ncol=3)
print(matrix)
 
# convert matrix to vector using c()
# function
a=c(matrix)
 
print(a)


 
 

Output:

 

 

Example 2:

 

R




# create a matrix with 16 elements
# with 4 rows and 4 columns
matrix=matrix(1:16,nrow=4,ncol=4)
print(matrix)
 
# convert matrix to vector using
# c() function
a=c(matrix)
 
print(a)


 
 

Output:

Method 2: Using as.vector() function

This function is used to convert matrix to vector so again simply passing the matrix name is enough.

Syntax: 

as.vector(matrix)

 

Example: 

R




# create a matrix with 12 elements
# with 4 rows and 3 columns
matrix=matrix(1:12,nrow=4,ncol=3)
print(matrix)
 
# convert matrix to vector using
# as.vector() function
a=as.vector(matrix)
 
print(a)


 
 

Output:

 

Example 2:

R




# create a matrix with 16 elements with 4 rows and 4 columns
matrix=matrix(1:16,nrow=4,ncol=4)
print(matrix)
 
# convert matrix to vector using as.vector() function
a=as.vector(matrix)
 
print(a)


 
 

Output
 

Convert Matrix to Vector in R

In this article, we are going to convert the given matrix into the vector in R programming language.

Similar Reads

Conversion of the matrix to vector by row

Method 1: Using c() function...

Conversion of the matrix to vector by column

...