In this tutorial, a vector is a single column matrix. A matrix is a 2 dimensional array.
Let’s begin by creating two matrices of equal sizes.
Input: a<-matrix(1:4,nrow=2,ncol=2) b<-matrix(seq(5,8),nrow=2,ncol=2) a b Output: 1 3 2 4 5 7 6 8
Addition and subtraction are then straightforward provided that each vector/matrix has the same size, i.e. the same number of rows and columns. Each element in matrix b is added to or subtracted from the corresponding element in a.
Input: a+b a-b Output: 6 10 8 12 -4 -4 -4 -4
Element-wise multiplication is when each element of a vector/matrix is multiplied by a single corresponding element in another. The vectors/matrices must have the same number of rows and/or columns.
Input: c<-matrix(1:6,nrow=3) d<-c(2,2) d*c c*d Output: 2 8 4 10 6 12 2 8 4 10 6 12 Input: c<-matrix(1:4,nrow =2,ncol=2) d<-matrix(5,9,nrow=2,ncol =2) c*d d*c Output: 5 15 10 20 5 15 10 20
Both operations give the same result in each instance
To multiply two matrices, we use the rather complicated construction %*%. In terms of matrices, the operation AxB is not generally the same as BxA, i.e. matrix multiplication is not associative. In addition, the matrices must be conformable. The number of columns in the first matrix must equal the number of rows in the second. This means that, in general, a matrix with m rows and n columns can multiply one with n rows and p columns, the result being a m x p matrix. Let's looks at the difference.
Input: a%*%b Output: 23 31 34 46
This is not the same as b%*%a.
Input: b%*%a Output: 19 43 22 50
Therefore, for different shaped matrices, only one order of multiplication may be possible.
In the next example, which operation will throw an error?