Frankoo
Frankoo

Reputation: 13

How to compare and find the min between a constant and each element of a matrix?

For example, I have a 3x3 matrix called "A" with numbers between 1 to 10, and a constant= 5. I would like to create another matrix 3x3 called "B" where each element is the minimum between A elements and the constant. I know i could do this easily with for loops, but is there any function or shorter way to do this?

example

A[1,1] = 2 -> B[1,1]=min(A[1,1],constant) ->B[1,1]=2

A[1,2]=10  -> B[1,2]=min(A[1,2],constant) ->B[1,2]=5

Upvotes: 1

Views: 124

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388962

You can use pmin :

set.seed(123)
A <- matrix(sample(1:10, 9), nrow = 3)
constant <- 5
pmin(A, constant)

#     [,1] [,2] [,3]
#[1,]    3    5    1
#[2,]    5    5    5
#[3,]    2    5    5

Upvotes: 1

Related Questions