Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use max on each element of a matrix

Tags:

r

max

matrix

> x <- array(-10:10, dim=c(4,5))
> x
     [,1] [,2] [,3] [,4] [,5]
[1,]  -10   -6   -2    2    6
[2,]   -9   -5   -1    3    7
[3,]   -8   -4    0    4    8
[4,]   -7   -3    1    5    9

How do I apply "max(x, 0)" to each element so that I get this matrix:

     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    2    6
[2,]    0    0    0    3    7
[3,]    0    0    0    4    8
[4,]    0    0    1    5    9
like image 902
ManInMoon Avatar asked May 22 '13 16:05

ManInMoon


1 Answers

Use pmax:

pmax(x,0)
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    0    0    0    2    6
#[2,]    0    0    0    3    7
#[3,]    0    0    0    4    8
#[4,]    0    0    1    5    9
like image 124
eddi Avatar answered Oct 23 '22 20:10

eddi