RCourse Lecture8 Calculations
RCourse Lecture8 Calculations
Basics of Calculations
::::
Matrix Operations
Shalabh
Department of Mathematics and Statistics
Indian Institute of Technology Kanpur
1
Multiplication of a matrix with a constant
> x <- matrix(nrow=4, ncol=2, data=1:8, byrow=T )
> x
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
[4,] 7 8
2
Matrix multiplication: operator %*%
3
Cross product of a matrix X, XX, with a function crossprod
5
Addition and subtraction of matrices (of same dimensions!) can be
executed with the usual operators + and -
> 4*x
[,1] [,2]
[1,] 4 8
[2,] 12 16
[3,] 20 24
[4,] 28 32
6
Addition and subtraction of matrices (of same dimensions!) can
be executed with the usual operators + and -
> x + 4*x
[,1] [,2]
[1,] 5 10
[2,] 15 20
[3,] 25 30
[4,] 35 40
> 4*x - x
[,1] [,2]
[1,] 3 6
[2,] 9 12
[3,] 15 18
[4,] 21 24
7
Access to rows, columns or submatrices:
> x <- matrix( nrow=5, ncol=3, byrow=T, data=1:15)
> x
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 4 5 6
[3,] 7 8 9
[4,] 10 11 12
[5,] 13 14 15
8
Access to rows, columns or submatrices:
> x[3,]
[1] 7 8 9
> x[,2]
[1] 2 5 8 11 14
9
Inverse of a matrix:
Example:
> y
[,1] [,2]
[1,] 84 100
[2,] 100 120
> solve(y)
[,1] [,2]
[1,] 1.50 -1.25
[2,] -1.25 1.05 10
Eigen Values and Eigen Vectors:
eigen() finds the eigen values and eigen vectors of a positive
definite matrix
Example:
> y
[,1] [,2]
[1,] 84 100
[2,] 100 120
> eigen(y)
$values
[1] 203.6070864 0.3929136
$vectors
[,1] [,2]
[1,] 0.6414230 -0.7671874
[2,] 0.7671874 0.6414230 11