Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to multiply the 2d matrices of a 3d array by a scalar in R?

Tags:

arrays

r

matrix

I have a 2x2x10 array of identity matrices, created with

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)

z = arr[,,1:10] * c(1:10)

However, I'm getting unexpected results. The first three 2x2 matrices of z shown below

, , 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?

like image 766
Ryan Oliver Lanham Avatar asked Oct 30 '20 21:10

Ryan Oliver Lanham


1 Answers

We need to replicate to make the lengths same

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]

like image 105
akrun Avatar answered Sep 21 '22 03:09

akrun