0
0
R Programmingprogramming~5 mins

Matrix arithmetic in R Programming

Choose your learning style9 modes available
Introduction
Matrix arithmetic helps you do math with tables of numbers easily, like adding, subtracting, or multiplying grids of values.
When you want to add or subtract two tables of numbers of the same size.
When you need to multiply two matrices to combine data or transform it.
When calculating things like rotations or scaling in graphics using matrices.
When solving systems of equations represented as matrices.
When working with data in rows and columns that need mathematical operations.
Syntax
R Programming
A + B       # Add two matrices
A - B       # Subtract matrix B from A
A %*% B     # Multiply two matrices
A * B       # Multiply matrices element-wise
solve(A)    # Find inverse of matrix A
Use %*% for matrix multiplication, not * which does element-wise multiplication.
Matrices must have compatible sizes for these operations to work.
Examples
Adds two 2x2 matrices element by element.
R Programming
A <- matrix(c(1,2,3,4), nrow=2)
B <- matrix(c(5,6,7,8), nrow=2)
A + B
Multiplies two 2x2 matrices using matrix multiplication rules.
R Programming
A <- matrix(c(1,2,3,4), nrow=2)
B <- matrix(c(5,6,7,8), nrow=2)
A %*% B
Multiplies every element of matrix A by 2.
R Programming
A <- matrix(c(1,2,3,4), nrow=2)
A * 2
Sample Program
This program creates two 2x2 matrices A and B, adds them, and multiplies them using matrix multiplication. It then prints the results.
R Programming
A <- matrix(c(1, 2, 3, 4), nrow=2)
B <- matrix(c(5, 6, 7, 8), nrow=2)

# Add matrices
sum_matrix <- A + B

# Multiply matrices
prod_matrix <- A %*% B

print("Sum of matrices:")
print(sum_matrix)

print("Product of matrices:")
print(prod_matrix)
OutputSuccess
Important Notes
Matrix addition and subtraction require matrices to have the same dimensions.
Matrix multiplication requires the number of columns in the first matrix to equal the number of rows in the second.
Use solve() to find the inverse of a square matrix if needed.
Summary
Matrix arithmetic lets you add, subtract, and multiply tables of numbers.
Use + and - for element-wise addition and subtraction.
Use %*% for matrix multiplication, which follows special rules.