Skip to content
Prev 312940 / 398503 Next

Large loops in R

HI,

I just wonder whether your code worked or not.
set.seed(8)
mat1<-matrix(sample(1:80,40,replace=TRUE),ncol=8)
set.seed(25)
mat2<-matrix(sample(1:160,40,replace=TRUE),ncol=8)
#Since the dimensions are the same, 
m<-1:5
n<-1:8
sum1<-0

for(i in 1:length(m)){
?for(j in 1:length(n)){
?sum1<-sum1+(((mat1[i,j]/d1)-(mat2[i,j]/d2))^2)
?}
?}
sum1
#[1] 15192.89

#Sara's code:
sum((mat1/d1 - mat2/d2)^2)
#[1] 15192.89
A.K.




----- Original Message -----
From: Charles Novaes de Santana <charles.santana at gmail.com>
To: "r-help at r-project.org" <r-help at r-project.org>
Cc: 
Sent: Tuesday, December 4, 2012 2:27 PM
Subject: Re: [R] Large loops in R

Dear Michael,

Thank you for your answer.

I have 2 matrices. Each position of the matrices is a weight. And I
need to calculate the following sum of differences:

Considering:
mat1 and mat2 - two matrices (each of them 48000 x 48000).
d1 and d2 - two constant values.

sum<-0;
for(i in 1:nrows1){
? ? ? ? ? ? ? ? ? ? ? ? for(j in 1:nrows2){
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? sum<-sum+ ( ( (mat1(i,j)/d1) -
(mat2(i,j)/d2) )^2 )
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? }

I was wondering if there is a better way to do this sum.

Thank you for your attention!

Best,

Charles

On Tue, Dec 4, 2012 at 7:54 PM, R. Michael Weylandt
<michael.weylandt at gmail.com> <michael.weylandt at gmail.com> wrote: