gpt4 book ai didi

r - 将矩阵的元素与向量值相乘

转载 作者:行者123 更新时间:2023-12-04 12:36:05 24 4
gpt4 key购买 nike

我有一个矩阵 M,我想创建 3 个额外的矩阵,其中每个额外的矩阵都有特定的 3x3 列切片 M 乘以向量中的值,然后我将生成的 3 个新矩阵存储在 列表中

##create the initial matrix
M <- matrix(1:20, nrow = 4)

[,1] [,2] [,3] [,4] [,5]
[1,] 1 5 9 13 17
[2,] 2 6 10 14 18
[3,] 3 7 11 15 19
[4,] 4 8 12 16 20

## coordinates in the matrix I want to alter
iy <- c(1, 2, 3)
ix <- c(1, 4, 5)
coords <- as.data.frame(cbind(ix, iy))


## multiplier values
multis <- c(0.1, 2, 100)

我想做的伪代码

mapply (function(multis, cords) {multis * M[coords$iy, coords$ix]})

结果应该是什么样的

  [[1]]
[,1] [,2] [,3] [,4] [,5]
[1,] 0.1 5 9 13.0 17.0
[2,] 2.0 6 10 1.4 18.0
[3,] 3.0 7 11 15.0 1.1
[4,] 4.0 8 12 16.0 20.0

[[2]]
[,1] [,2] [,3] [,4] [,5]
[1,] 2 5 9 13 17
[2,] 2 6 10 28 18
[3,] 3 7 11 15 38
[4,] 4 8 12 16 20

[[3]]
[,1] [,2] [,3] [,4] [,5]
[1,] 100 5 9 13 17
[2,] 2 6 10 1400 18
[3,] 3 7 11 15 1900
[4,] 4 8 12 16 20

最佳答案

首先需要将coords 强制转换为矩阵进行索引,然后反转列顺序。然后它只是一个简单的 lapply() 循环。

coords <- as.matrix(coords)[, 2:1]
lapply(multis, function(x) {
M[coords] <- M[coords] * x
M
})

导致

[[1]]
[,1] [,2] [,3] [,4] [,5]
[1,] 0.1 5 9 13.0 17.0
[2,] 2.0 6 10 1.4 18.0
[3,] 3.0 7 11 15.0 1.9
[4,] 4.0 8 12 16.0 20.0

[[2]]
[,1] [,2] [,3] [,4] [,5]
[1,] 2 5 9 13 17
[2,] 2 6 10 28 18
[3,] 3 7 11 15 38
[4,] 4 8 12 16 20

[[3]]
[,1] [,2] [,3] [,4] [,5]
[1,] 100 5 9 13 17
[2,] 2 6 10 1400 18
[3,] 3 7 11 15 1900
[4,] 4 8 12 16 20

关于r - 将矩阵的元素与向量值相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48677257/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com