5

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!

Sielu
  • 129
  • 2
  • 2
  • 6

2 Answers2

11

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
CHP
  • 16,981
  • 4
  • 38
  • 57
  • I had no idea, thet these operators can be applied to matrices as well. Thank you so much! :) – Sielu Nov 26 '13 at 14:34
0

For matrix addition or subtraction you can write like this.

A + B, A-B

A
     [,1] [,2] [,3]
[1,]    3    3    3
[2,]    3    3    3
[3,]    3    3    3

B
     [,1] [,2] [,3]
[1,]    2    2    2
[2,]    2    2    2
[3,]    2    2    2

But, in case of multiplication if you write A* B this will give wrong ans.

A*B
     [,1] [,2] [,3]
[1,]    6    6    6
[2,]    6    6    6
[3,]    6    6    6

because matrix multiplication process is not like this. It only multiplies it's respective rows and columns values.

The correct answer for matrix multiplication will be.

A %*% B
     [,1] [,2] [,3]
[1,]   18   18   18
[2,]   18   18   18
[3,]   18   18   18
Anwoy
  • 1
  • 2