[英]Is there a way to multiply the 2d matrices of a 3d array by a scalar in R?
I have a 2x2x10 array of identity matrices, created with我有一个 2x2x10 的单位矩阵数组,用
arr = array(diag(2), dim=c(2,2,10))
I'm looking to multiply each 2x2 matrix within that array by a scalar c(1:10)
我希望将该数组中的每个 2x2 矩阵乘以标量
c(1:10)
z = arr[,,1:10] * c(1:10)
However, I'm getting unexpected results.但是,我得到了意想不到的结果。 The first three 2x2 matrices of
z
shown below z
的前三个 2x2 矩阵如下所示
, , 1
[,1] [,2]
[1,] 1 0
[2,] 0 4
, , 2
[,1] [,2]
[1,] 5 0
[2,] 0 8
, , 3
[,1] [,2]
[1,] 9 0
[2,] 0 2
Am I missing something?我错过了什么吗?
We need to rep
licate to make the lengths same我们需要
rep
licate使长度相同
arr[,,1:10] * rep(1:10, each = length(arr[,, 1]))
or else 1 gets multiplied by the first element of arr[, , 1]
2 with the second element of arr[,, 1]
and due to recycling the elements of shorter vector is recycled until the length
of arr[, , 1:10]
否则 1 将乘以
arr[, , 1]
的第一个元素 2 与arr[,, 1]
的第二个元素,并且由于循环使用较短的向量的元素被循环使用,直到arr[, , 1:10]
的length
arr[, , 1:10]
sweep()
is designed for this: sweep()
是为此而设计的:
sweep(arr, 3, 1:10, `*`)
, , 1
[,1] [,2]
[1,] 1 0
[2,] 0 1
, , 2
[,1] [,2]
[1,] 2 0
[2,] 0 2
, , 3
[,1] [,2]
[1,] 3 0
[2,] 0 3
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.