Q:

How to write R code to make a matrix transformation

I have a 7x7 matrix and a vector of size 5, and I want to to change the matrix entries to -1 or 1 values according to the following rule:

if the matrix element matches any value in the vector, it is changed to 1
if the matrix element doesn't match any element in the vector, it is changed to -1. 

In the end I will get a transformed matrix with -1 and 1 values only. 
How can I write the R code for this problem? 

A:

First, I create some example data:
m <- matrix(sample(1:10, 49, replace = TRUE),
            ncol = 7)
v <- 1:5

This line transforms the matrix according to your specification:
m2 <- matrix((m %in% v) * 2 - 1, ncol = ncol(m))    

m %in% v returns TRUE for all elements of m that are contained in v and FALSE for all the others.  If arithmetic is done with logical variables in R, TRUE is converted to 1 and FALSE to zero.  Therefore,
TRUE * 2 - 1 = 1 * 2 - 1 = 1
FALSE * 2 - 1 = 0 * 2 - 1 = -1

The result of the computation is a vector, which again must be converted to a matrix using matrix(). 

A:

Using the same data as @stibu:
m[]<-ifelse(m %in% v,1,-1)
m
     [,1] [,2] [,3] [,4] [,5] [,6] [,7]
[1,]    1    1   -1   -1    1    1   -1
[2,]    1   -1   -1   -1    1   -1   -1
[3,]    1   -1    1   -1   -1    1    1
[4,]    1    1   -1   -1   -1   -1   -1
[5,]    1   -1   -1    1   -1    1    1
[6,]    1   -1   -1    1   -1    1   -1
[7,]    1   -1   -1   -1    1    1    1

On a side note, Stibu's solution is faster (using a dataset with 7000 rows):
microbenchmark(stibu=matrix((m %in% v) * 2 - 1, ncol = ncol(m)), iod=matrix(ifelse(m %in% v,1,-1),ncol=ncol(m)))
Unit: microseconds
  expr    min      lq     mean  median      uq    max neval
 stibu  441.5  447.25  574.993  450.95  462.20 5352.2   100
   iod 1070.6 1080.70 1363.861 1113.50 1154.45 4974.5   100

but I think mine is more generalizable if you don't need 1 and -1 as the output but something else.