######################################### # Tutorial on functions # with vector calculus ######################################### # vector magnitude magnitude<-function(x){ n<-length(x) res<-0 for (i in 1:n){ res<-res+x[i]^2 } return(sqrt(res)) } # another way to do it: # I use R's own sum-function # is much faster! # You can try it with a long vector # and compare the speed of both functions # with vector x<-rep(1,1000000) magnitude2<-function(x){ x<-x*x return(sqrt(sum(x))) } dotproduct<-function(x,y){ n<-length(x) n2<-length(y) if (n2!=n){ res<-NA } else { res<-0 for (i in 1:n){ res<-res+x[i]*y[i] } } return(res) }