[英]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.例如,我有一个名为“A”的 3x3 矩阵,其数字介于 1 到 10 之间,常数 = 5。我想创建另一个名为“B”的 3x3 矩阵,其中每个元素都是 A 元素和常数之间的最小值。 I know i could do this easily with for loops, but is there any function or shorter way to do this?
我知道我可以使用 for 循环轻松做到这一点,但是有没有 function 或更短的方法来做到这一点?
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
You can use pmin
:您可以使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.