lundi 17 octobre 2016

Matrix function in R

I'm trying to create a function that will transform a matrix (MATR1). It should multiply every element that is a prime by 2 and return the new matrix (MATR2). This is what I've done so far:

MATR1 <- matrix()

My.Func <- function(MATR1)
  MATR2 <- matrix(nrow(MATR1), ncol(MATR1))
  for (i in 1:nrow(MATR1)) {
    for(j in 2:ncol(MATR1)) {
      if (MATR1[i,j]%%2 == 0) {
        MATR2[i,j] <- MATR1[i,j]/2
      } else {MATR2[i,j] <- MATR1[i,j]}
    }
  } 
  return(matrix(MATR2, nrow(MATR1)))

But I can't get it to work. Can anyone see where I've made a mistake? Appreciate all help!

Aucun commentaire:

Enregistrer un commentaire