Читать книгу The Big R-Book - Philippe J. S. De Brouwer - Страница 68

Question #3 Dot product

Оглавление

Write a function for the dot-product for matrices. Add also some security checks. Finally, compare your results with the “%*%-operator.”

dot-product

The dot-product is pre-defined via the %*% opeartor. Note that the function t() creates the transposed vector or matrix.

# Example of the dot-product: a <- c(1:3) a %*% a ## [,1] ## [1,] 14 a %*% t(a) ## [,1] [,2] [,3] ## [1,] 1 2 3 ## [2,] 2 4 6 ## [3,] 3 6 9 t(a) %*% a ## [,1] ## [1,] 14 # Define A: A <- matrix(:8, nrow = 3, byrow = TRUE) # Test products: A %*% a ## [,1] ## [1,] 8 ## [2,] 26 ## [3,] 44 A %*% t(a) # this is bound to fail! ## Error in A %*% t(a): non-conformable arguments A %*% A ## [,1] [,2] [,3] ## [1,] 15 18 21 ## [2,] 42 54 66 ## [3,] 69 90 111

There are also other operations possible on matrices. For example the quotient works as follows:

A %/% A ## [,1] [,2] [,3] ## [1,] NA 1 1 ## [2,] 1 1 1 ## [3,] 1 1 1

The Big R-Book

Подняться наверх