Open In App

How to multiply a matrix by its transpose while ignoring missing values in R ?

Last Updated : 21 Apr, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to multiply a matrix by its transpose while ignoring the missing values in R Programming Language. It can be done by replacing all the NAs by 0 in the matrix

The replacement of values, can be performed in O(n*m), where n is the number of rows and m is the number of columns. Replacing by 0s doesn’t affect the multiplicative product, and therefore, this is an effective solution. The transpose can then be calculated by using t(matrix). The product can be calculated by the following syntax in R : 

m1 %*% m2 , where m1 and m2 are the matrices involved. 

If m1 is the matrix of n*m dimensions and m2 of m*n (since it’s the transpose), the product matrix obtained is a square matrix is n * n .

Example 1:

R




# declaring matrix 
mat = matrix(c(1, NA, 2, 3, NA, 4), ncol = 2)
  
# replacing matrix NA with 0s
mat[is.na(mat)] = 0
  
# printing original matrix
print ("Original Matrix")
print (mat)
  
# calculating transpose of the
# matrix
transmat = t(mat)
print ("Transpose Matrix")
print (transmat)
  
# calculating product of matrices
prod = mat%*%transmat
print ("Product Matrix")
print (prod)


Output:

[1] "Original Matrix"
    [,1] [,2]
[1,]    1    3
[2,]    0    0
[3,]    2    4
[1] "Transpose Matrix"
    [,1] [,2] [,3]
[1,]    1    0    2
[2,]    3    0    4
[1] "Product Matrix"
    [,1] [,2] [,3]
[1,]   10    0   14
[2,]    0    0    0
[3,]   14    0   20

The original matrix is of the dimensions 3 x 2 and the transpose is of the dimension 2×3. On replacing the missing values with 0 and multiplying these two together, we obtain the product matrix equivalent to 3×3 square matrix. 

Example 2: The original matrix is of the dimensions 1 x 3 and the transpose is of the dimension 3×1. On replacing the missing values with 0 and multiplying these two together, we obtain the product matrix equivalent to 1×1 square matrix, which is basically a singular cell matrix. 

R




# declaring matrix 
mat = matrix(c(10, NA, 7), ncol = 3)
  
# replacing matrix NA with 0s
mat[is.na(mat)] = 0
  
# printing original matrix
print ("Original Matrix")
print (mat)
  
# calculating transpose of the
# matrix
transmat = t(mat)
print ("Transpose Matrix")
print (transmat)
  
# calculating product of matrices
prod = mat%*%transmat
print ("Product Matrix")
print (prod)


Output

[1] "Original Matrix"
    [,1] [,2] [,3]
[1,]   10   0    7
[1] "Transpose Matrix"
    [,1]
[1,]   10
[2,]    0
[3,]    7
[1] "Product Matrix"
    [,1]
[1,]   149


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads