# Some examples of matrix computations # # Create a 3*2 matrix > A <- matrix(c(1,3,2,5,6,4),byrow=T,ncol=2) > A [,1] [,2] [1,] 1 3 [2,] 2 5 [3,] 6 4 # Create a 2*2 matrix > B <- matrix(c(2,2,3,1),byrow=T,ncol=2) > B [,1] [,2] [1,] 2 2 [2,] 3 1 # Matrix multiplication > A%*%B [,1] [,2] [1,] 11 5 [2,] 19 9 [3,] 24 16 # Square each element of a matrix > B^2 [,1] [,2] [1,] 4 4 [2,] 9 1 # Multiply a square matrix by itself > B%*%B [,1] [,2] [1,] 10 6 [2,] 9 7 # Extract the diagonal of a square matrix > diag(B) [1] 2 1 > sum(diag(B)) [1] 3 # Concatenate a matrix (i.e. stack the columns) > c(A) [1] 1 2 6 3 5 4 # Transpose a matrix > t(A) [,1] [,2] [,3] [1,] 1 2 6 [2,] 3 5 4 # Bind the columns of two matrices > cbind(t(A),B) [,1] [,2] [,3] [,4] [,5] [1,] 1 2 6 2 2 [2,] 3 5 4 3 1