0

I have two data matrix as below

firstMatrix <- matrix(runif(10),500, 100)
   secondMatrix <- matrix(runif(10),500, 25)

I want to get the Sum ROOT of square residual from firstMatrix regards to the secondMatrix. this is where I am stuck in

myopt3 <- function(firstMatrix,secondMatrix) {
resid2 <- (secondMatrix-firstMatrix[,i])^2
  sum(resid2)
}

I want each time, I get the residual of firstMatrix according to the secondMatrix in a way that get the residual for each four columns of firstMatrix based on one column of secondMatrix.

for example

(secondMatrix[,1]-firstMatrix[,1])^2
(secondMatrix[,1]-firstMatrix[,2])^2
(secondMatrix[,1]-firstMatrix[,3])^2
(secondMatrix[,1]-firstMatrix[,4])^2

then

(secondMatrix[,2]-firstMatrix[,5])^2
(secondMatrix[,2]-firstMatrix[,6])^2
(secondMatrix[,2]-firstMatrix[,7])^2
(secondMatrix[,2]-firstMatrix[,8])^2

then ...

until the end and save all the values in another matrix This is what I am trying to do on this example data

nik
  • 2,500
  • 5
  • 21
  • 48

1 Answers1

0

From this post you can replicate columns of your secondMatrix :

secondMatrix = secondMatrix[ ,rep(1:ncol(secondMatrix), times = 4)]

Then you do the sum of the squared difference :

diff = colSums((secondMatrix - firstMatrix)^2)
Community
  • 1
  • 1
ClementWalter
  • 4,814
  • 1
  • 32
  • 54
  • I want to use it inside the loop, please modify your answer and give an output so that I can accept your answer – nik May 23 '16 at 10:28
  • I don't get your point, my `diff` is what you expect I guess. From a practical point of view, for loop should be banned as very inefficient, or written in C/C++. – ClementWalter May 23 '16 at 10:47