i have got 2 matrices.
matrix 1
id1 id2 id3 id4 id5 row1 0.4 0.5 0.2 0.1 0.3
matrix 2
id1 id2 id3 id4 id5 row1 1.1 1.2 1.3 4.1 4.0 row2 3.4 2.6 1.2 3.2 2.1 row3 4.5 6.2 1.1 1.3 3.1
i trying match column vectors ids , run following formula each column in matrix 1 , 2 independently of remaining column ids
(matrix1$id*matrix2$id)^2+2(matrix1$id*matrix2$id)+(1-matrix1$id)^2
please suggest way loop function across ids after matching based on column ids.
mat1 <- matrix(nrow=1,ncol=5) mat1 <- as.matrix(t(c(0.4, 0.5, 0.2, 0.1, 0.3))) mat2 <- matrix(nrow=3, ncol=5) mat2[1,] <- c(1.1, 1.2, 1.3, 4.1, 4.0) mat2[2,] <- c(3.4, 2.6, 1.2, 3.2, 2.1) mat2[3,] <- c(4.5, 6.2, 1.1, 1.3, 3.1) result <- matrix(nrow = 3, ncol = 5) for(i in 1:ncol(mat1)){ result[,i] <- t((mat1[,i]*mat2[,i])^2 + 2*(mat1[,i]*mat2[,i]) + (1 - mat1[,i])^2) } result [,1] [,2] [,3] [,4] [,5] [1,] 1.4336 1.81 1.2276 1.7981 4.3300 [2,] 4.9296 4.54 1.1776 1.5524 2.1469 [3,] 7.2000 16.06 1.1284 1.0869 3.2149
you can use column names instead of indices or send equation in for
loop function , use apply
.