Ryan Oliver Lanham
Ryan Oliver Lanham

Reputation: 461

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

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?

Upvotes: 5

Views: 354

Answers (2)

lroha
lroha

Reputation: 34566

sweep() is designed for this:

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

...

Upvotes: 2

akrun
akrun

Reputation: 887501

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]

Upvotes: 3

Related Questions