Open In App

Matrix Algebra in R

Last Updated : 17 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In mathematics, ‘matrix‘ refers to the rectangular arrangement of numbers, symbols or expressions which are further arranged in columns and rows. The only difference of matrix in R and mathematics is that in R programming language, the elements should be of homogeneous types(i.e, same data types). Hence, the matrix is called two-dimensional because it is being worked on rows and columns.   

Creating Matrix

Here we are going to create matrix using R programming language.

The syntax  used to describe matrix is, 

Syntax: matrix(data, nrow, ncol, byrow, dimname) 

Where, 

  • data -> these includes the data elements of the matrix , 
  • nrow -> number of rows, 
  • ncol -> number of columns
  • byrow -> it shows whether the elements are arranged in rows or columns( byrow = TRUE (for rows) and byrow=FALSE(for columns)),
  • dimnames -> names of rows and columns. 

R




matrix(c(5, 6, 4, 1, 8, 4), nrow = 2, 
       ncol = 3, byrow = TRUE)
matrix


Output:

A matrix: 2 × 3 of type dbl
5 6 4
1 8 4

Matrix with a constant value

The syntax for the matrix having constant value,

Syntax: matrix(s,m,n)

Where, s -> the constant value, m->number of rows, n->number of columns                           

R




matrix(4,2,2)
matrix


Output:

A matrix: 2 × 2 of type dbl
4 4
4 4

Operation on Matrix

Now, let’s see the binary operations(=, -, *, / ) on matrices with the following code

R




R1 = matrix(c(4,-2,3,5), nrow=2,ncol=2)
R1
  
R2 = matrix(c(0,6,3,1), nrow=2,ncol=2)
R2
  
# addition of matrices R1 and R2
sum = R1 + R2
sum
  
# subtraction
difference = R1 - R2
difference
  
# multiplication
product = R1*R2
product
  
# division
result = R1/R2
result


Output:

 

Rank Matrix 

Rank refers to the number of linearly independent columns(rows) in a matrix. We will import ‘rankMatrix’ function from the ‘Matrix’ package in R as there is no base function available for the calculation of the rank of a matrix.

Syntax: rankMatrix(matrix name)

R




R1 <- matrix(c(10,20,20,40), 
             ncol = 2, 
             byrow = TRUE)
  
# Equivalent to:
library(Matrix)
rankMatrix(R1)[1]


Output:

1

We can also find the rank by using the ‘qr’ function which calculates the ‘QR Decomposition’. 

Diagonal Matrix

This diagonal matrix can be constructed using ‘diag’ function. 

Syntax: diag(c(data)) 

R




diag(c(22,-14,56))


Output:

22 0 0
0 -14 0
0 0 56

The diagonal function also helps to replace or extract the diagonal of a matrix.

Determinant in Matrix

Generally, the determinant of any matrix is shown by ImatrixI . In R, we will use the ‘det’ function for the calculation.

Syntax: det(matrix name)

R




R1 <- matrix(c(3,9,7,2),
             ncol = 2, 
             byrow = TRUE)
det(R1)


Output:

-57

Inverse in Matrix

We can find the inverse of a matrix Using solve() function                                                           

R




R1 <- matrix(c(19,11,2,33),
             ncol = 2, 
             byrow = TRUE)
solve(R1)


Output:

0.054545455 -0.01818182
-0.003305785 0.03140496

Transpose in Matrix

In this, we will use ‘t()’ function.

Syntax: t(matrix name)

R




R1 <- matrix(c(19,11,2,33),
             ncol = 2,
             byrow = TRUE)
t(R1)


Output:

19 2
11 33

Eigenvalues and Eigenvectors

eigenvalues and eigenvectors both are calculated by using eigen() function. The eigenvalues are stored on the ‘values’ of the list and by default it will display the decreasing order. 

Syntax: eigen(matrix name) $values 

For eigenvectors, they are stored in ‘vectors’ of the list. 

Syntax: eigen(matrix name) $ vectors . 

R




R1 <- matrix(c(19,11,2,33), 
             ncol = 2,
             byrow = TRUE)
  
 # show the eigen values of matrix R1
eigen(R1)$values
  
# show the eigen vectors of matrix R1
eigen(R1)$vectors 


Output:

34.426149773176417.5738502268236
A matrix: 2 × 2 of type dbl
-0.5805852 -0.9916999
-0.8141995 0.1285739

The matrix must be square for the calculation of power. Since there is no built-in function to calculate the power of the matrix. So, we can use any two of the methods, i.e., ‘%^%’ operator of the ‘expm’ package and the’ matrix.power’ function of the ‘matrixcalc’ package. 

R




R1 <- matrix(c(19,11,2,33),
             ncol = 2, 
             byrow = TRUE)
R1^2


Output:

A matrix: 2 × 2 of type dbl
361 121
4 1089

There are various ways of doing the matrix multiplication which include, matrix crossproduct, exterior product, multiplication by a scalar, matrix multiplication, and Kronecker product. 

Exterior Product

If the 2 vectors having s and t dimensions then their exterior(or outer) product s x t is a matrix. In R, we will use ‘%o%’ operator to find the exterior product of a matrix.

R




R1 <- matrix(c(2,7,1,5), ncol = 2, byrow = TRUE)
R2 <- matrix(c(3,8,4,0),ncol = 2,byrow = TRUE)
R1 %o% R2
  
# Equivalent to:
outer(R1, R2, FUN = "*")


 

 

Matrix Cross Product

In this, the matrix’s product is counted in a very fast and efficient way by using ‘crossprod’ function and for multiplying a matrix with transpose, we use ‘tcrossprod’ function. It computes the cross product between corresponding rows or columns. Syntax for cross and tcross product are,  crossprod(matrix1,matrix2) and tcrossprod(matrix1,matrix2) respectively.

R




R1 = matrix(c(0,3,5,1),nrow=2)
R2 = matrix(c(2,4,1,6),nrow=2)
  
# it will show the cross product
crossprod(R1, R2)  
  
# it will show the multiplication with
# transpose of any one or both of the matrix
tcrossprod(R1,R2)  


Output:

A matrix: 2 × 2 of type dbl
12 18
14 11
A matrix: 2 × 2 of type dbl
5 30
7 18

Multiplication by  a scalar

In this, we use ‘*’ operator to multiply a scalar with a matrix. When performing a multiplication of a matrix by a scalar quantity, the resulting matrix will always have the same dimensions as the original matrix in the multiplication. The magnitude of the result matrix only changes and not the dimensions. 

R




R1 = matrix(c(0,3,5,1),nrow=2)
4*R1 # let us take 4 as the scalar value 


Output:

A matrix: 2 × 2 of type dbl
0 20
12 4

Matrix Multiplication

Here, ‘%*%’ operator is used for matrix multiplication. Syntax is, (matrix1)%*%(matrix2). Example, 

R




R1 = matrix(c(0,3,5,1),nrow=2)
R2 = matrix(c(1,-2,4,6),nrow=2)
R1%*%R2


Output:

A matrix: 2 × 2 of type dbl
-10 30
1 18

Kronecker product

It is another form of representing the product of two matrices and is further calculated by ‘%x%’ operator. It helps to solve difficult problems in linear algebra and its applications. It is basically an operation that transforms two matrices into a larger matrix which contains all the possible products of the entries of the two matrices. 

R




R1 = matrix(c(0,3,5,1),nrow=2)
R2 = matrix(c(1,-2,4,6),nrow=2)
R1%x%R2


Output:

A matrix: 4 × 4 of type dbl
0 0 5 20
0 0 -10 30
3 12 1 4
-6 18 -2 6

Now, we will see the vectors and its operations.  In R, ‘vector‘ is a basic data structure which contains the homogeneous elements. These elements can be logical, double, integer, character, complex or raw. Vector is generally created by using ‘c()’ function. For example, variable<-c(1:4). 

Addition of Vectors

Here, we can also add integer and decimal data types but we can’t add 2 different data types like string and integer. The syntax for addition of vectors is, (vector1)+(vector2). 3 rules for the addition of vectors are:- 

  • For addition, we have to use ‘+’ operator.
  • If the 2 vector’s lengths are equal, then, we can add simply.
  • But, if the length of 2 vectors are not equal, then, the shorter one is repeated until its length goes equal to the longer one. Most importantly, if the longer vector is not an integer multiple of the shorter one then it will give a ‘warning message’ in the output.

R




# addition of different length of 2 vectors
s<-c(1:3) # first vector
t<-c(12:15) # second vector
  
sum<-s+t
sum


Output:

13 
15 
17 
16

Multiplication of Vectors

Two vectors are multiplied by each other by their position, that is, ‘ index’. Here, the element of the first vector which has an index of 1 is multiplied by the element of the second vector which has an index of 1.  Similarly, the elements of the first vector at the index 2 and 3 were multiplied to the element of the second vector which has indexes 2 and 3 respectively. The index of the vector in R starts with 1 and not 0. The rule of multiplication of vectors is:- It follows the commutative property of multiplication according to which when two numbers are multiplied with each other, then the result remains the same regardless of their order.

R




# multiplication of 2 vectors of same length
s<-c(1:3) # first vector
t<-c(12:14) # second vector                
product<-s*t
product


Output:

12
26
42


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads