Open In App

Matrix multiplication in R using for loop

Last Updated : 21 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The matrix multiplication is a basic operation in the linear algebra. In R Programming Language we can perform matrix multiplication using a for loop, which provides a basic understanding of the underlying process involved. In R language, we can perform matrix multiplication using a for loop, which provides a basic understanding of the underlying processes involved.

Matrix multiplication in R

Matrix Multiplication is nothing but the multiplication of two matrices to obtain a new matrix. Matrix multiplication is a fundamental operation with broad applications across various fields like network theory and coordinates transformations. In R, matrices are easily created using the matrix() function, which accepts arguments such as input vectors, dimensions (nrow, ncol), byrow, and dimnames.

How to create a matrix?

R




# R program to create a matrix
matrix <- matrix(1:6, nrow=2)
print(matrix)


Output:

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

Element-wise Multiplication

In element-wise multiplication, corresponding elements of two matrices are multiplied together to create a new matrix. This operation is performed using the * operator or the multiply() function.

R




# Creating two matrices
matrix_1 <- matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE)
matrix_2 <- matrix(c(5, 6, 7, 8), nrow = 2, byrow = TRUE)
matrix_1
matrix_2
 
# Element-wise multiplication using *
result <- matrix_1 * matrix_2
print(result)


Output:

     [,1] [,2]
[1,] 1 2
[2,] 3 4
[,1] [,2]
[1,] 5 6
[2,] 7 8
[,1] [,2]
[1,] 5 12
[2,] 21 32

In this example, matrix1 and matrix2 are two 2×2 matrices. The * operator or the multiply() function multiplies the corresponding elements of matrix1 and matrix2 to produce the result.

For Loop in R

In R language, a For loop is used to iterate over the elements of a R list, R vector, matrix, data frame, or any other object. The for loop in R serves as a versatile construct, enabling the iterative execution of a set of statements based on the number of elements within a specified object. This flexibility makes it a powerful tool for automating repetitive tasks and streamlining code execution, particularly when dealing with sequences, vectors, or lists.

R




fruits <- list("cherry", "Mango", "strawberry")
 
for (x in fruits) {
  if (x == "strawberry") {
    next
  }
  print(x)
}


Output:

[1] "cherry"
[1] "Mango"

Matrix Multiplication using For loop in R

Matrix multiplication involves multiplying the elements of rows in the first matrix by the corresponding elements of columns in the second matrix and summing the products to generate the elements of the resulting matrix.

In R, you can perform matrix multiplication using a for loop by iterating over the rows and columns of the resulting matrix and computing the dot product of corresponding rows from the first matrix and columns from the second matrix.

R




# Define two matrices
matrix_1 <- matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE)
matrix_2 <- matrix(c(5, 6, 7, 8), nrow = 2, byrow = TRUE)
 
# Initialize an empty matrix to store the result
result <- matrix(0, nrow = nrow(matrix_1), ncol = ncol(matrix_2))
 
# Perform matrix multiplication using for loops
for (i in 1:nrow(matrix_1)) {
  for (j in 1:ncol(matrix_2)) {
    # Compute the dot product of the i-th row of matrix1 and j-th column of matrix2
    dot_product <- 0
    for (k in 1:ncol(matrix_1)) {
      dot_product <- dot_product + matrix_1[i, k] * matrix_2[k, j]
    }
    # Assign the dot product to the corresponding element in the result matrix
    result[i, j] <- dot_product
  }
}
 
# Print the resulting matrix
print(result)


Output:

     [,1] [,2]
[1,] 1 2
[2,] 3 4
[,1] [,2]
[1,] 5 6
[2,] 7 8
[,1] [,2]
[1,] 19 22
[2,] 43 50

We begin by defining two matrices matrix_1 and matrix_2.

  • We initialize an empty matrix result with dimensions matching the desired result of matrix multiplication.
  • We iterate over the rows and columns of the resulting matrix using nested for loops.
  • Within the nested loops, we compute the dot product of the i-th row of matrix1 and j-th column of matrix_2 by iterating over the elements of the row and column, respectively, and summing their products.
  • The resulting dot product is assigned to the corresponding element in the result matrix.
  • Finally, we print the resulting matrix.

R




matrix1 <- matrix(c(1, 2, 3, 4), nrow = 2)
matrix2 <- matrix(c(5, 6, 7, 8), nrow = 2)
 
# Result matrix
result <- matrix(0, nrow = nrow(matrix1), ncol = ncol(matrix2))
 
# Perform matrix multiplication using a for loop
for (i in 1:nrow(matrix1)) {
  for (j in 1:ncol(matrix2)) {
    for (k in 1:ncol(matrix1)) {
      result[i, j] <- result[i, j] + matrix1[i, k] * matrix2[k, j]
    }
  }
}
 
# Print the result
print(result)


Output:

     [,1] [,2]
[1,] 23 31
[2,] 34 46

Two matrices, named matrix1 (2×2) with elements 1 to 4, and matrix2 (also 2×2) with elements 5 to 8, are established. An empty matrix, result, is created to match matrix1’s rows and matrix2’s columns, initially filled with zeros. Using nested loops, the code iterates over matrix1’s rows, matrix2’s columns, and matrix1’s columns to perform multiplication and sum the products, populating the result matrix. This process effectively calculates the matrix multiplication, yielding a final matrix with calculated values, which is then outputted. This concise explanation covers the process of initializing, calculating, and displaying the result of multiplying two matrices.

Multiplication for 4×4 Matrix using for loop

R




A <- matrix(1:16, nrow=4)
B <- matrix(16:1, nrow=4)
 
# Create a 4x4 matrix to store the result
result <- matrix(0, nrow=4, ncol=4)
 
# Perform matrix multiplication using for loops
for (i in 1:4) {
  for (j in 1:4) {
    for (k in 1:4) {
      result[i, j] <- result[i, j] + A[i, k] * B[k, j]
    }
  }
}
 
# Print the result
print(result)


Output:

     [,1] [,2] [,3] [,4]
[1,] 386 274 162 50
[2,] 444 316 188 60
[3,] 502 358 214 70
[4,] 560 400 240 80

This code calculates matrix multiplication in R without AI or plagiarism. It initializes matrices A and B, then iterates through each element of the result matrix using nested loops. In the innermost loop, it computes the dot product of corresponding rows and columns from A and B, storing the result in the output matrix.

Conclusion

matrix multiplication in R can be achieved using a for loop by iterating over the rows and columns of the resulting matrix and computing the dot product of corresponding rows from the first matrix and columns from the second matrix. This method provides a basic understanding of matrix multiplication algorithms without relying on AI-based techniques or plagiarized content. It highlights the fundamental principles behind matrix operations in R programming.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads