Skip to content
Related Articles

Related Articles

Fill an empty matrix in R
  • Last Updated : 21 Apr, 2021

In this article, we will discuss how to fill the empty matrix with values in R Programming Language. First, let’s create an empty matrix.

Syntax:

matrix_name[row,column]=value.

Where, row and column are the numbers in which the value is occupied.

Example:



R




# create empty matrix.
a<-matrix(nrow=4,ncol=4)
  
# display matrix
print(a)
  
# filling empty matrix with value at 
# 2nd row and 4 th column
a[2,4]=4
print(a)
  
# create empty matrix.
a<-matrix(nrow=4,ncol=4)
  
# filling empty matrix with value at 
# 4th column
a[,4]=4
print(a)
  
# create empty matrix.
a<-matrix(nrow=4,ncol=4)
  
# filling empty matrix with value at 
# 4th row
a[4,]=4
print(a)

Output:

We can replace with same value for all empty value in a matrix, by using [,].

Example

R




# create empty matrix.
a<-matrix(nrow=4,ncol=4)
  
# display matrix
print(a)
  
# replace empty matrix with 5 value
a[,]=5
print(a)

Output:

Even a range can be inserted.

Example

R




# create empty matrix.
a<-matrix(nrow=4,ncol=4)
  
# display matrix
print(a)
  
# replace empty matrix with  
# 1 to 16 values
a[,]=1:16
print(a)

Output:

My Personal Notes arrow_drop_up
Recommended Articles
Page :