yoman
yoman

Reputation: 33

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!

Upvotes: 1

Views: 72

Answers (1)

alistaire
alistaire

Reputation: 43364

Use vectorized operations instead of for loops. You'll also need a function to determine whether numbers are prime. There are several possible algorithms, but none built into base R. I'll use numbers::isPrime here, though you can write your own prime sieve or other algorithm from scratch if you like.

First, some setup:

library(numbers)

set.seed(47)    # for reproducibility
mat <- matrix(rpois(100, 10), 10)    # sample matrix

mat
##       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
##  [1,]   16    6    8    7   12   14   10   12    9    14
##  [2,]   12    4    7    8   13    9    7    5   14    15
##  [3,]   10   12    4   15   15   14   12   10   10    12
##  [4,]    9    8    3    9   16   13   12   10    9     9
##  [5,]   10    7    9    9   14   14   10   13    8    11
##  [6,]    6    7    9   13   12    6    7   10    8    11
##  [7,]   10   11    8    8    9    5   10   14   12    11
##  [8,]   14    8   10    7   10   12    8    5   12    14
##  [9,]    4   14    6    5   10   13    7   12   10     6
## [10,]    7    7   10   13   15   16   13    7    9     9

To define the function, assign to the subset that meets the criteria:

double_primes <- function(m){
    m[isPrime(m)] <- m[isPrime(m)] * 2; 
    m
}

double_primes(mat)
##       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
##  [1,]   16    6    8   14   12   14   10   12    9    14
##  [2,]   12    4   14    8   26    9   14   10   14    15
##  [3,]   10   12    4   15   15   14   12   10   10    12
##  [4,]    9    8    6    9   16   26   12   10    9     9
##  [5,]   10   14    9    9   14   14   10   26    8    22
##  [6,]    6   14    9   26   12    6   14   10    8    22
##  [7,]   10   22    8    8    9   10   10   14   12    22
##  [8,]   14    8   10   14   10   12    8   10   12    14
##  [9,]    4   14    6   10   10   26   14   12   10     6
## [10,]   14   14   10   26   15   16   26   14    9     9

Upvotes: 3

Related Questions