Introduction
Matrix operations are fundamental in various fields such as mathematics, data analysis, and machine learning. This guide will walk you through writing an R program that performs matrix addition and subtraction.
Problem Statement
Create an R program that:
- Creates two matrices with the same dimensions.
- Adds the two matrices.
- Subtracts the second matrix from the first.
- Displays the resulting matrices.
Example:
- Input: Two 2×2 matrices:
- Matrix A:
1 2 | 3 4
- Matrix B:
5 6 | 7 8
- Matrix A:
- Output:
- Addition Result:
6 8 | 10 12
- Subtraction Result:
-4 -4 | -4 -4
- Addition Result:
Solution Steps
- Create Two Matrices: Use the
matrix()
function to create two matrices with the same dimensions. - Add the Matrices: Use the
+
operator to perform element-wise addition of the two matrices. - Subtract the Matrices: Use the
-
operator to perform element-wise subtraction of the two matrices. - Display the Results: Use the
print()
function to display the resulting matrices.
R Program
# R Program to Add and Subtract Two Matrices # Author: Ramesh Fadatare # Step 1: Create two matrices matrix_A <- matrix(c(1, 2, 3, 4), nrow = 2, ncol = 2) matrix_B <- matrix(c(5, 6, 7, 8), nrow = 2, ncol = 2) # Step 2: Add the matrices addition_result <- matrix_A + matrix_B # Step 3: Subtract the matrices subtraction_result <- matrix_A - matrix_B # Step 4: Display the results print("Matrix A:") print(matrix_A) print("Matrix B:") print(matrix_B) print("Addition of Matrix A and Matrix B:") print(addition_result) print("Subtraction of Matrix B from Matrix A:") print(subtraction_result)
Explanation
Step 1: Create Two Matrices
- The
matrix()
function is used to creatematrix_A
andmatrix_B
, each with dimensions 2×2. matrix_A
is populated with values1, 2, 3, 4
, andmatrix_B
with5, 6, 7, 8
.
Step 2: Add the Matrices
- The
+
operator performs element-wise addition ofmatrix_A
andmatrix_B
. The result is stored inaddition_result
.
Step 3: Subtract the Matrices
- The
-
operator performs element-wise subtraction ofmatrix_B
frommatrix_A
. The result is stored insubtraction_result
.
Step 4: Display the Results
- The
print()
function is used to displaymatrix_A
,matrix_B
, the result of the addition, and the result of the subtraction.
Output Example
Example:
[1] "Matrix A:" [,1] [,2] [1,] 1 3 [2,] 2 4 [1] "Matrix B:" [,1] [,2] [1,] 5 7 [2,] 6 8 [1] "Addition of Matrix A and Matrix B:" [,1] [,2] [1,] 6 10 [2,] 8 12 [1] "Subtraction of Matrix B from Matrix A:" [,1] [,2] [1,] -4 -4 [2,] -4 -4
Conclusion
This R program demonstrates how to perform matrix addition and subtraction using basic arithmetic operations. It covers fundamental concepts such as matrix creation, element-wise operations, and displaying results. Understanding matrix operations is essential for various applications in data analysis, statistics, and scientific computing, making this example valuable for beginners learning R programming.