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 in R using for loop

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.

Similar Reads

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....

Matrix Multiplication using For loop in R

...

Contact Us