Reputation: 764
Suppose I have a list of two matrices and
t=c(1,2,3,4).
> y_list
[[1]]
[,1] [,2]
[1,] 1 11
[2,] 2 12
[3,] 3 13
[4,] 4 14
[5,] 5 15
[6,] 6 16
[7,] 7 17
[8,] 8 18
[9,] 9 19
[10,] 10 20
[[2]]
[,1] [,2]
[1,] 21 31
[2,] 22 32
[3,] 23 33
[4,] 24 34
[5,] 25 35
[6,] 26 36
[7,] 27 37
[8,] 28 38
[9,] 29 39
[10,] 30 40
I want to do another list of two matrices of order 10 by 4(length of t). I can do it for individual matrix. For the first matrix
n.iter=nrow(y_list[[1]])
t.i=c(01,2,3,4)
y_list.1=matrix(NA, nrow = n.iter, ncol=length(t.i))
for( iter in 1:n.iter){
for (t in 1:length(t.i)){
y_list.1[iter,t]=y_list[[1]][iter,1]+y_list[[1]][iter,2]*t.i[t]
}
}
y_list.1
> y_list.1
[,1] [,2] [,3] [,4]
[1,] 12 23 34 45
[2,] 14 26 38 50
[3,] 16 29 42 55
[4,] 18 32 46 60
[5,] 20 35 50 65
[6,] 22 38 54 70
[7,] 24 41 58 75
[8,] 26 44 62 80
[9,] 28 47 66 85
[10,] 30 50 70 90
I want to the same task for the second matrix in the list y_list. How can I do another list of two matrices of order 10 by 4 using for loop? Thanks in advance
Upvotes: 0
Views: 815
Reputation: 12569
First reduce your calculation to:
y_list <- list(matrix(1:20, 10), matrix(21:40, 10))
t.i <- c(1, 2, 3, 4)
y_list.1 <- y_list[[1]][,1] + tcrossprod(y_list[[1]][,2], t.i)
y_list.1
Now it is clear that you can do for your list of matrices:
lapply(y_list, function(y) y[,1] + tcrossprod(y[,2], t.i))
The result is a list of the new calculated matrices.
Upvotes: 2