Tuesday, August 6, 2024

Matrix in R language

                                         Matrix


    A matrix in R is a two-dimensional array that can store data of the same type. Here’s a comprehensive guide to creating, manipulating, and using matrices in R.


1. Creating a Matrix

You can create a matrix using the matrix() function. The basic syntax is:

matrix(data, nrow = , ncol = , byrow = FALSE, dimnames = NULL)


  • data: The data to fill the matrix.

  • nrow: Number of rows.

  • ncol: Number of columns.

  • byrow: Logical indicating whether to fill the matrix by rows (default is FALSE, which fills by columns).

  • dimnames: Optional list of row and column names.



Example 1: Basic Matrix Creation


# Create a 2x3 matrix with default filling by columns

mat <- matrix(1:6, nrow = 2, ncol = 3)

print(mat)

     [,1] [,2] [,3]

[1,]    1    3    5

[2,]    2    4    6


# Create a 2x3 matrix with filling by rows

mat_byrow <- matrix(1:6, nrow = 2, ncol = 3, byrow = TRUE)

print(mat_byrow)

     [,1] [,2] [,3]

[1,]    1    2    3

[2,]    4    5    6


# Create a matrix


mat <- matrix(1:6, nrow = 2, ncol = 3)


# Assign row and column names

rownames(mat) <- c("Row1", "Row2")

colnames(mat) <- c("Col1", "Col2", "Col3")


print(mat)

     Col1 Col2 Col3

Row1    1    3    5

Row2    2    4    6


3. Accessing Elements

You can access and modify matrix elements using indexing.

Example: Accessing and Modifying Elements

# Access element at 1st row, 2nd column


element <- mat[1, 2]

print(element)  # Output: 3


# Modify element at 2nd row, 3rd column


mat[2, 3] <- 10

print(mat)


     Col1 Col2 Col3

Row1    1    3    5

Row2    2    4   10


4. Matrix Operations

Matrices support various operations, including arithmetic operations, transposition, and more.

Example: Matrix Arithmetic


# Create two matrices

mat1 <- matrix(1:4, nrow = 2)

mat2 <- matrix(5:8, nrow = 2)


# Element-wise addition

mat_sum <- mat1 + mat2

print(mat_sum)


# Element-wise multiplication

mat_prod <- mat1 * mat2

print(mat_prod)


Output for addition:

    [,1] [,2]

[1,]    6    8

[2,]   10   12


Output for multiplication:

    [,1] [,2]

[1,]    5   12

[2,]   14   32


Example: Matrix Transposition


# Transpose a matrix


mat_transposed <- t(mat)

print(mat_transposed)

Output:

    Row1 Row2

Col1    1    2

Col2    3    4

Col3    5   10


5. Matrix Functions

R provides several built-in functions for matrices:

Example: Matrix Functions


# Create a matrix

mat <- matrix(1:9, nrow = 3)


# Calculate the determinant

determinant <- det(mat)

print(determinant)

[1] 0


# Calculate the inverse (if the matrix is square and invertible)

> mat4 <- matrix(c(4, 7, 2, 6), nrow = 2, byrow = TRUE)

> print(mat4)

     [,1] [,2]

[1,]    4    7

[2,]    2    6

> inv_mat4 <- solve(mat4)

> print(inv_mat4)

     [,1] [,2]

[1,]  0.6 -0.7

[2,] -0.2  0.4



# Eigenvalues and eigenvectors

eigen_values <- eigen(mat)$values

eigen_vectors <- eigen(mat)$vectors

print(eigen_values)

[1]  1.611684e+01 -1.116844e+00 -5.700691e-16


print(eigen_vectors)

           [,1]       [,2]       [,3]

[1,] -0.4645473 -0.8829060  0.4082483

[2,] -0.5707955 -0.2395204 -0.8164966

[3,] -0.6770438  0.4038651  0.4082483


6. Combining Matrices

You can combine matrices using rbind() for row-binding and cbind() for column-binding.

Example: Combining Matrices


# Create two matrices

mat1 <- matrix(1:4, nrow = 2)

mat2 <- matrix(5:8, nrow = 2)


# Row-bind matrices

combined_rows <- rbind(mat1, mat2)

print(combined_rows)

     [,1] [,2]

[1,]    1    3

[2,]    2    4

[3,]    5    7

[4,]    6    8



# Column-bind matrices

combined_cols <- cbind(mat1, mat2)

print(combined_cols)

     [,1] [,2] [,3] [,4]

[1,]    1    3    5    7

[2,]    2    4    6    8


# calculating diff of matrices


> # Define matrices


> mat1 <- matrix(c(1, 2, 3, 4), nrow = 2, byrow = TRUE)

> mat2 <- matrix(c(5, 6, 7, 8), nrow = 2, byrow = TRUE)

> # Get dimensions


> num_of_rows <- nrow(mat1)

> num_of_cols <- ncol(mat1)

> # Initialize result matrix with zeros


> add <- matrix(0, nrow = num_of_rows, ncol = num_of_cols)

> # Perform matrix addition


> for (row in 1:num_of_rows) {

+    for (col in 1:num_of_cols) {

+        add[row, col] <- mat1[row, col] + mat2[row, col]

+    }

+ }


> # Print the result


> cat("Result of Matrix Addition:\n")


Result of Matrix Addition:

> print(add)

     [,1] [,2]

[1,]    6    8

[2,]   10   12

>












No comments:

Post a Comment