October 2017
Beginner to intermediate
236 pages
7h 38m
English
Write a function using a for loop to execute the targeted operation. Also, write another function without using a loop. Let's take a look at the following steps and see how we can do the preceding two tasks:
loopOperation <- function(mat){ out<-matrix(NA, nrow = ncol(mat), ncol = ncol(mat)) for(i in 1:ncol(mat)){ for(j in 1:ncol(mat)){ colI <- mat[,i] colJ <- mat[,j] out[i,j] <- t(colI) %*% colJ } } return(out) }
vectorizedOp <- function(mat){ return(t(mat) %*% mat) } library(microbenchmark) # To compare performance of the functions ...