Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: subtraction of elements of a matrix from the elements of another matrix

I am trying to apply an equation to two matrices. Since I am a beginner R user, it seems very difficult to me. I would be greatful if you could give me some advice.

I have two similarity matrices:

> r
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0    4    2    2    5    5
[2,]    4    0    8    3    3    2
[3,]    2    8    0    4    4    3
[4,]    2    3    4    0    0    3
[5,]    5    3    4    0    0    5
[6,]    5    2    3    3    5    0

> nr
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    0    4    7    2    4    3
[2,]    4    0    5    2    3    2
[3,]    7    5    0    3    2    2
[4,]    2    2    3    0    7    2
[5,]    4    3    2    7    0    5
[6,]    3    2    2    2    5    0

And I wolud like to apply to these the following:

sum((r[i,j]-nr[i,j])^2)/6

My great problem is to extract elements of nr from the elements r. If I substitute nr[i,j] with a number, for example 0.4 then the following works perfectly:

s<-numeric()
for (i in 1:nrow(r))
{
  for (j in 1:ncol(r))
{
    s[k]<-sum((r[i,j]-0.4)^2)/6
}
}
> s
[1] 0.02666667

But I can't figure out how could I modify this code to solve the original problem. I would appreciate any kind of help/suggestion. Thanks!

like image 909
Sielu Avatar asked Jan 11 '23 19:01

Sielu


1 Answers

normal operators like +, -, *, / and ^ do element wise operations. So simply (r - nr)^2/6 will do the trick for you.

r
##      [,1] [,2] [,3]
## [1,]    2    2    2
## [2,]    2    2    2
## [3,]    2    2    2

nr
##      [,1] [,2] [,3]
## [1,]    3    3    3
## [2,]    3    3    3
## [3,]    3    3    3


r * nr
##      [,1] [,2] [,3]
## [1,]    6    6    6
## [2,]    6    6    6
## [3,]    6    6    6


r - nr
##      [,1] [,2] [,3]
## [1,]   -1   -1   -1
## [2,]   -1   -1   -1
## [3,]   -1   -1   -1


(r - nr)^2/6
##           [,1]      [,2]      [,3]
## [1,] 0.1666667 0.1666667 0.1666667
## [2,] 0.1666667 0.1666667 0.1666667
## [3,] 0.1666667 0.1666667 0.1666667
like image 105
CHP Avatar answered Jan 24 '23 19:01

CHP