Module 6 – Linear Algebra in R (Part 2)

 

# 1. Matrix Addition & Subtraction

A <- matrix(c(2, 0, 1, 3), ncol = 2)

B <- matrix(c(5, 2, 4, -1), ncol = 2)

# Addition

A_plus_B <- A + B

A_plus_B

# Subtraction

A_minus_B <- A - B

A_minus_B

Explanation : Matrix addition and subtraction work element-by-element on matrices of the same size, combining or contrasting values at the same positions. This is useful for quickly aggregating or comparing structured numeric data

# 2.Create a Diagonal Matrix

D <- diag(c(4, 1, 2, 3))

D

Explanation : diag() places the supplied numbers along the main diagonal and fills all other entries with zeros. Diagonal matrices are commonly used for identity/scaling operations and as building blocks in linear algebra.

# 3.Construct a Custom 5 × 5 Matrix

M <- diag(3, 5, 5)          

M[1, 2:5] <- 1              

M[2:5, 1] <- 2    

M

Explanation : started with a diagonal of 3’s and then used indexing to set the first row (except the diagonal) to 1 and the first column (below the diagonal) to 2. This shows how to programmatically target and modify specific matrix positions to create a structured pattern.


OUTPUT

> # Matrix Addition & Subtraction
> A <- matrix(c(2, 0, 1, 3), ncol = 2)
> B <- matrix(c(5, 2, 4, -1), ncol = 2)
> # Addition
> A_plus_B <- A + B
> A_plus_B
     [,1] [,2]
[1,]    7    5
[2,]    2    2
> # Subtraction
> A_minus_B <- A - B
> A_minus_B
     [,1] [,2]
[1,]   -3   -3
[2,]   -2    4
> # Create a Diagonal Matrix
> D <- diag(c(4, 1, 2, 3))
> D
     [,1] [,2] [,3] [,4]
[1,]    4    0    0    0
[2,]    0    1    0    0
[3,]    0    0    2    0
[4,]    0    0    0    3
> # Construct a Custom 5 × 5 Matrix
> M <- diag(3, 5, 5)          
> M[1, 2:5] <- 1              
> M[2:5, 1] <- 2    
> M
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    1    1    1    1
[2,]    2    3    0    0    0
[3,]    2    0    3    0    0
[4,]    2    0    0    3    0
[5,]    2    0    0    0    3






Comments

Popular posts from this blog

Assignment

Assignment #5