Saturday, February 16, 2013

Basic Matrix Operations with R

A while back I posted a series on basic matrix operations in VB.NET. Those posts looked at using arrays to represent matrices in VB.NET, how to add and subtract matrices, and how to transpose and multiply matrices.

I want to revisit those operations in R, mostly as an object lesson in using the right tool for the right job. If you look back at those previous posts, it took over a hundred lines of code to build, populate and operate against two small matrices. Here are the same matrices and the same operations in R.

> #First build the matrices A and B
> A <- matrix(
+ c(1,2,3,5,8,13,21,34,55,89,144,233), #These are the values in the matrix A.
+ nrow=3, #This is the number of rows in A.
+ ncol=4, #This is the number of columns in A.
+ byrow=TRUE)
>
> B <- matrix(
+ c(2,3,5,7,11,13,17,19,23,29,31,37), #These are the values in the matrix B.
+ nrow=3, #This is the number of rows in B.
+ ncol=4, #This is the number of columns in B.
+ byrow=TRUE)
>
> A
[,1] [,2] [,3] [,4]
[1,]    1    2    3    5
[2,]    8   13   21   34
[3,]   55   89  144  233
>
> B
[,1] [,2] [,3] [,4]
[1,]    2    3    5    7
[2,]   11   13   17   19
[3,]   23   29   31   37
>
> #Add A and B.
> A+B
[,1] [,2] [,3] [,4]
[1,]    3    5    8   12
[2,]   19   26   38   53
[3,]   78  118  175  270
>
> #Subtract B from A.
> A-B
[,1] [,2] [,3] [,4]
[1,]   -1   -1   -2   -2
[2,]   -3    0    4   15
[3,]   32   60  113  196
>
> #Transpose B.
> Bt=t(B)
> Bt
[,1] [,2] [,3]
[1,]    2   11   23
[2,]    3   13   29
[3,]    5   17   31
[4,]    7   19   37
>
> #Multiply A and Bt.
> A%*%Bt
[,1] [,2]  [,3]
[1,]   58  183   359
[2,]  398 1260  2470
[3,] 2728 8637 16931