Q:

Ensuring values in matrix are between a set range?

I am new to R and I am working on function to manipulate a set of data.
I have a 20 by 5 matrix of values, to that I add a random number between -1 to 1. How can I ensure that all the values in the matrix stay between 0-10 in an efficient and fast manner (without using a loop to check a single value at a time).
These are the rules:

If a value is greater than 10, change it to 10 
If a value is less
thatn 0, change it to 0

Any help is appreciated. Thanks!

A:

Something like
m[] <- pmax(0,pmin(10,m))

The m[] on the lefthand side (rather than m) ensures that the matrix keeps its structure.
Here's a (probably unnecessary) example:
lwr <- 0; upr <- 10
set.seed(101)
mRaw <- matrix(runif(100, lwr, upr), nrow=20) 
m1 <- sample(c(-1,1),size=100,replace=TRUE)
mAdded <- m1 + mRaw

Now clamp:
mAdded[] <- pmax(lwr,pmin(upr,mAdded))
str(mAdded)
## still a matrix: num [1:20, 1:5] 2.72 0 6.1 7.58 3.5 ...
range(mAdded)  ## 0 10

