Open In App

Fill Matrix With Loop in R

Last Updated : 02 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see how to fill a matrix with a loop in R Programming Language.

To create a matrix in R you need to use the function called matrix(). The arguments to this matrix() are the set of elements in the vector. You have to pass how many numbers of rows and how many numbers of columns you want to have in your matrix.

Example 1:

In this example, we’re creating a matrix with 5 rows and 5 columns with NA and filling the matrix with 90 using for loop.

R




# create matrix with NA with 5 
# rows and 5 columns
matrixinp = matrix(data=NA, nrow=5, ncol=5)
  
# display matrix
print(matrixinp)
  
# fill the elements with some 
# 90 in a matrix
for(j in 1:5){
   for(i in 1:5){
        matrixinp[i,j] = 90
   }
}
  
# display filled matrix
print(matrixinp)


Output:

     [,1] [,2] [,3] [,4] [,5]
[1,]   NA   NA   NA   NA   NA
[2,]   NA   NA   NA   NA   NA
[3,]   NA   NA   NA   NA   NA
[4,]   NA   NA   NA   NA   NA
[5,]   NA   NA   NA   NA   NA
     [,1] [,2] [,3] [,4] [,5]
[1,]   90   90   90   90   90
[2,]   90   90   90   90   90
[3,]   90   90   90   90   90
[4,]   90   90   90   90   90
[5,]   90   90   90   90   90

Example 2:

In this example, we are creating a matrix with 5 rows and 5 columns with 0 and filling the matrix with j iteration values using for loop.

R




# create matrix with NA with 5 
# rows and 5 columns
matrixinp = matrix(data=0, nrow=5, ncol=5)
  
# display matrix
print(matrixinp)
  
# fill the elements with j values
# in a matrix
for(j in 1:5){
   for(i in 1:5){
        matrixinp[i,j] = j
   }
}
  
# display filled matrix
print(matrixinp)


Output:

     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    0    0    0    0
[3,]    0    0    0    0    0
[4,]    0    0    0    0    0
[5,]    0    0    0    0    0
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    4    5
[2,]    1    2    3    4    5
[3,]    1    2    3    4    5
[4,]    1    2    3    4    5
[5,]    1    2    3    4    5


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads