简体   繁体   English

如何比较并找到常数和矩阵的每个元素之间的最小值?

[英]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.

相关问题 如何找到矩阵每一行的最小值和最大值? - How to find min and max for each row of a matrix? 如何将列表中的每个元素与其他元素进行比较,并将结果输出为 R 中的成对比较矩阵? - How do I compare each element in a list with each other element and outpt the results as a pairwise comparison matrix in R? 使用 r base function 找到矩阵中每一行的相对最小值,但每个最小值在不同的列 - use r base function to find the relatively min value of each row in matrix but each min value at different column 我如何将时间序列的每一行与 R 中的常数进行比较 - How do i compare each row of a timeseries against a constant in R 比较/匹配/查找 R 中数据帧/矩阵之间的相似值 - Compare/match/find similar value between data frame/matrix in R 如何有效地将矩阵的每一行与R中列表的每个部分进行比较? - How to efficiently compare each row of a matrix to each section of a list in R? 查找每个组的最小值 - Find min for each group 如何通过在每次迭代中保留原始矩阵来在 for 循环中添加常量? - How to add a constant in a for loop by keeping the original matrix in each iteration? 如何在r中矩阵的每一行中找到第一个非零元素? - How to find the first non-zero element in each row of a matrix in r? 在R中,有了矩阵列表,如何快速找到列表中每个矩阵的第一行和第二行之间的差异? - In R, with a list of matrices, how can I quickly find the difference between the first and second row in each matrix in the list?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM