Everyday R Code (19) – A function example to compare loops and vectorization speed

#to compare speed of 2 methods: loops and vectorization

n=10

#generate 100 numbers between 1 and 1000, and then make a 10 by 10 matrix

A=matrix(runif(100,1,1000),nrow=n,ncol=n)

B=matrix(runif(100,1,100),nrow=n,ncol=n)

 

#method 1

A%*%B

#get system.time to compare with the other method

system.time(A%*%B)

 

#method 2

#using a function

MultiplyMatrices=function(A,B,n){

R=matrix(data=0,nrow=n,ncol=n)

for (i in 1:n)

for (j in 1:n)

for (k in 1:n) R[i,j]=R[i,j]+A[i,k]*B[k,j]

return(R)

}

#get system.time to compare with the other method

system.time(MultiplyMatrices(A,B,n))

 

Conclusion after comparison:

Speed result refer to the featured image. Unit is second.

Vectorization is fast and loops are slow.

Be the first to comment

Leave a Reply

Your email address will not be published.


*