0

I want to be able to store many matrices under 1 variable and then sequentially mulitply them with other matrices. I thought a list would do the job, but it's causing me some problems.

This is my input

j = list(matrix(c(0,1,2,3),nrow=2,ncol=2,byrow=TRUE), matrix(c(7,6,5,4),nrow=2,ncol=2,byrow=TRUE))

j[1]
j[1]%*%j[2]
t(j[1])
t(j[1])%*%j[1]

This is my output

> j = list(matrix(c(0,1,2,3),nrow=2,ncol=2,byrow=TRUE), matrix(c(7,6,5,4),nrow=2,ncol=2,byrow=TRUE))
> j[1]
[[1]]
     [,1] [,2]
[1,]    0    1
[2,]    2    3

> j[1]%*%j[2]
Error in j[1] %*% j[2] : requires numeric/complex matrix/vector arguments
> t(j[1])
     [,1]     
[1,] Numeric,4
> t(j[1])%*%j[1]
Error in t(j[1]) %*% j[1] : 
  requires numeric/complex matrix/vector arguments

Thanks in advance.

1 Answers1

0

When you do j[1] you get

#[[1]]
#     [,1] [,2]
#[1,]    0    1
#[2,]    2    3

which is still a list.

class(j[1])
#[1] "list"

What you needed instead was j[[1]] whose class is matrix

class(j[[1]])
#[1] "matrix"

j[[1]] %*% j[[2]]
#     [,1] [,2]
#[1,]    5    4
#[2,]   29   24

t(j[[1]]) %*% j[[1]]
#     [,1] [,2]
#[1,]    4    6
#[2,]    6   10

I would suggest reading through this post to understand difference between indexing operators.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213