Linear Algebra in R, create and invert matrices

This is a simple test case of creating a random 2×2 matrix, performing its inversion, and multiplying them. We will also use MS Excel to check our computations
Create a 2×2 matrix

> mNP <- matrix(rnorm(4),nrow=2,ncol=2)

This command used the matrix() function . This first argument, the datasets, uses rnorm() function to generate 4 random variates, and the next two arguments explain that those are to be ordered in a matrix of 2 rows by 2 columns. Now let’s display the matrix

> mNP
[,1] [,2]
[1,] 0.5644179 -0.4694577
[2,] 0.7707571 0.1500823

Next, we use solve() function to invert the matrix, and display the output

> mNP_inv <- solve(mNP)
> mNP_inv
[,1] [,2]
[1,] 0.3360953 1.051306
[2,] -1.7260381 1.263961

Finally, we use the %*% operator to to the algebraic multiplication of the matrices and check if we arrive to I

> mNP %*% mNP_inv
[,1] [,2]
[1,] 1 0
[2,] 0 1

If you would want to do the last operation in Excel, as a check, then let’s suppose that the first matrix sits in fields A1,B1,A2,B2 and the second one sits in fields D1,E1,D2,E2. Their multiplication product would be:
Top left, top right
=A1*D1+B1*D2 =A1*E1+B1*E2
Bottom left, bottom right
=A2*D1+B2*D2 =A2*E1+B2*E2

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.