I am trying to learn parallelism in R. I have written a code where I have a 50*50 matrix from the value 1 to 250000. For each element in the matrix, I am looking for its neighbor with the lowest value. The neighbors can be in a diagonal position too. Then I am replacing the element itself with the lowest neighbor. The amount of time taken for running this code is about 4.5 seconds on my computer. If it is possible to do, could anyone help me make the for loops parallel? Here is the Code Snippet
start_time <- Sys.time()
myMatrix <- matrix(1:250000, nrow=500) # a 500 * 500 matrix from 1 to 250000
indexBound <- function(row,col) { # this function is to check if the indexes are out of bound
if(row<0 || col <0 || row > 500 || col >500){
return (FALSE)
}
else{
return (TRUE)
}
}
for(row in 1:nrow(myMatrix)){
for(col in 1:ncol(myMatrix)){
li <- list()
if(indexBound(row-1,col-1)){
li <- c(li,myMatrix[row-1,col-1])
}
if(indexBound(row-1,col)){
li <- c(li,myMatrix[row-1,col])
}
if(indexBound(row-1,col+1)){
li <- c(li,myMatrix[row-1,col+1])
}
if(indexBound(row,col-1)){
li <- c(li,myMatrix[row,col-1])
}
if(indexBound(row-1,col+1)){
li <- c(li,myMatrix[row,col+1])
}
if(indexBound(row+1,col-1)){
li <- c(li,myMatrix[row+1,col-1])
}
if(indexBound(row+1,col)){
li <- c(li,myMatrix[row+1,col])
}
if(indexBound(row+1,col+1)){
li <- c(li, myMatrix[row+1,col+1])
}
min = Reduce(min,li) #find the lowest value from the list
myMatrix[row,col] = min
}
}
end_time <- Sys.time()
end_time - start_time
Thank you for your response.