R Program to Perform Matrix Multiplication

1. Introduction

Matrices are rectangular arrays of numbers, symbols, or expressions. In many scientific, engineering, and data analysis applications, matrix multiplication is a crucial operation. For two matrices to be multipliable, the number of columns in the first matrix should equal the number of rows in the second matrix. This guide will illustrate how to multiply two matrices in the R programming language.

2. Program Overview

Our program will:

1. Prompt the user for the dimensions of two matrices.

2. Ask the user to input the elements of both matrices.

3. Multiply the matrices if they are multipliable.

4. Display the resultant matrix.

3. Code Program

# Prompt the user for dimensions of the matrices
cat("Enter the dimensions of the first matrix (rows columns): ")
dimensions1 <- as.integer(unlist(strsplit(readLines(n=1), " ")))
cat("Enter the dimensions of the second matrix (rows columns): ")
dimensions2 <- as.integer(unlist(strsplit(readLines(n=1), " ")))

# Check if matrix multiplication is possible
if(dimensions1[2] != dimensions2[1]) {
  cat("Matrix multiplication is not possible with the given dimensions.\n")
} else {

  # Input elements for the first matrix
  matrix1 <- matrix(0, nrow=dimensions1[1], ncol=dimensions1[2])
  cat("Enter the elements of the first matrix, row-wise:\n")
  for(i in 1:dimensions1[1]) {
    row <- as.numeric(unlist(strsplit(readLines(n=1), " ")))
    matrix1[i,] <- row
  }

  # Input elements for the second matrix
  matrix2 <- matrix(0, nrow=dimensions2[1], ncol=dimensions2[2])
  cat("Enter the elements of the second matrix, row-wise:\n")
  for(i in 1:dimensions2[1]) {
    row <- as.numeric(unlist(strsplit(readLines(n=1), " ")))
    matrix2[i,] <- row
  }

  # Multiply matrices
  result <- matrix1 %*% matrix2

  # Display the result
  cat("Resultant matrix after multiplication:\n")
  print(result)
}

Output:

Enter the dimensions of the first matrix (rows columns): 2 2
Enter the dimensions of the second matrix (rows columns): 2 2
Enter the elements of the first matrix, row-wise:
1 2
3 4
Enter the elements of the second matrix, row-wise:
1 2
3 4
Resultant matrix after multiplication:
     [,1] [,2]
[1,]    7   10
[2,]   15   22

4. Step By Step Explanation

1. The program prompts the user for the dimensions of two matrices.

2. It then checks the feasibility of matrix multiplication based on the entered dimensions.

3. If matrix multiplication is viable, the user is asked to provide the elements for both matrices.

4. The matrices are multiplied using the %*% operator.

5. The resultant matrix is then displayed.

5. Running this Program in RStudio


Comments