Hi everyone,
I've got a function written in R that I want to convert into VBA. The function takes in 2 arguments a matrix of data and a tolerance level (scalar). I ideally would like the data input in an Excel spreadsheet - matrix and scalar and output the data to a location on another spreadsheet. This is my function in R:
# read in matrix 'x' and scalar 'tol'
# x is a square matrix
PowerMethod <- function(x, tol) {
# calculate covariance matrix of x
my.mat <- var(x, na.method="available")
# find the number of rows or columns of x
matSize <- dim(my.mat)[1]
# create a new matrix of the output data
eigenVec <- matrix(NA, nrow=matSize, ncol=matSize)
eigenVal <- rep(NA, matSize)
# for the length of the rows/columns of x do this
for(j in 1:matSize) {
# initial guess for x
x <- rep(1, matSize)
# calculate yk
yk <- my.mat%*%x
# n1 and n2 are the normalised vectors of x and yk for the tolerance
n1 <- (1/sqrt(sum(x^2)))*x
n2 <- (1/sqrt(sum(yk^2)))*yk
# if tolerance level isn't satisfied then do while loop
while(any(abs(n1-n2)>tol)) {
# calculate beta which is the element of yk with the largest magnitude
beta <- yk[abs(yk)==max(abs(yk))]
# update the value of x
x <- (1/beta)*yk
yk <- my.mat%*%x
# update the values of n1 and n2
n1 <- (1/sqrt(sum(x^2)))*x
n2 <- (1/sqrt(sum(yk^2)))*yk
}
# put the values of n1 and beta into the output matrix and vector
eigenVec[,j] <- n1
eigenVal[j] <- beta
# update the value of the covariance matrix
my.mat <- my.mat - eigenVal[j]*eigenVec[,j]%*%t(eigenVec[,j])
}
# output the matrix and vector of eigenvectors and eigenvalues
list(values=eigenVal, vectors=eigenVec)
}
Would really appreciate any help on this.
John
Bookmarks