R Program to Multiply Two Matrices

Introduction

Matrix multiplication is a fundamental operation in linear algebra, used extensively in various fields such as data analysis, machine learning, and scientific computing. In matrix multiplication, the number of columns in the first matrix must be equal to the number of rows in the second matrix. This guide will walk you through writing an R program that multiplies two matrices.

Problem Statement

Create an R program that:

  • Creates two matrices that are compatible for multiplication.
  • Multiplies the two matrices.
  • Displays the resulting matrix.

Example:

  • Input:
    • Matrix A (2×3): 1 2 3 | 4 5 6
    • Matrix B (3×2): 7 8 | 9 10 | 11 12
  • Output:
    • Resulting Matrix (2×2): 58 64 | 139 154

Solution Steps

  1. Create Two Matrices: Use the matrix() function to create two matrices that can be multiplied.
  2. Multiply the Matrices: Use the %*% operator to perform matrix multiplication.
  3. Display the Resulting Matrix: Use the print() function to display the resulting matrix.

R Program

# R Program to Multiply Two Matrices
# Author: Ramesh Fadatare

# Step 1: Create two matrices
matrix_A <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 2, ncol = 3)
matrix_B <- matrix(c(7, 8, 9, 10, 11, 12), nrow = 3, ncol = 2)

# Step 2: Multiply the matrices
result_matrix <- matrix_A %*% matrix_B

# Step 3: Display the resulting matrix
print("Matrix A:")
print(matrix_A)

print("Matrix B:")
print(matrix_B)

print("Resulting Matrix after Multiplication:")
print(result_matrix)

Explanation

Step 1: Create Two Matrices

  • The matrix() function is used to create matrix_A (a 2×3 matrix) and matrix_B (a 3×2 matrix).
  • matrix_A is populated with values 1, 2, 3, 4, 5, 6, and matrix_B with 7, 8, 9, 10, 11, 12.

Step 2: Multiply the Matrices

  • The %*% operator is used for matrix multiplication. This operator performs matrix multiplication according to the rules of linear algebra, where the elements of the resulting matrix are calculated as the dot products of corresponding rows and columns.

Step 3: Display the Resulting Matrix

  • The print() function is used to display matrix_A, matrix_B, and the resulting matrix after multiplication.

Output Example

Example:

[1] "Matrix A:"
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

[1] "Matrix B:"
     [,1] [,2]
[1,]    7   10
[2,]    8   11
[3,]    9   12

[1] "Resulting Matrix after Multiplication:"
     [,1] [,2]
[1,]   58   64
[2,]  139  154

Conclusion

This R program demonstrates how to perform matrix multiplication using the %*% operator. It covers basic operations such as matrix creation, matrix multiplication, and displaying the resulting matrix. Understanding matrix multiplication is crucial for many applications in data analysis, machine learning, and scientific computing, making this example valuable for anyone learning R programming.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top