Milaa
Milaa

Reputation: 419

Make matrix by subtracting each element of vector from other element of it

Consider the vector a <- c(17.4, 17.2, 17.0, 16.9, 17.0, 17.4)

How to build the following matrix:

 A <-    17.4-17.4   17.2-17.4  17.0-17.4  16.9-17.4  17.0-17.4   17.4-17.4
         17.4-17.2   17.2-17.2  17.4-17.2  16.9-17.2  17.0-17.2   17.4-17.2
         17.4-17.0   17.2-17.0  17.0-17.0  16.9-17.0  17.0-17.0   17.4-17.0
         17.4-16.9   17.2-16.9  17.0-16.9  16.9-16.9  17.0-16.9   17.4-16.9
         17.4-17.0   17.2-17.0  17.0-17.0  16.9-17.0  17.0-17.0   17.4-17.0
         17.4-17.4   17.2-17.4  17.0-17.4  16.9-17.4  17.0-17.4   17.4-17.4

I want to subtract all vector elements from the first element and store the result in the first row of matrix A, then subtract all vector elements from the second element and store the result in the second row of matrix A, and so on until the last element of vector an is reached.

The final result should be:

A <- 0.0   -0.2   -0.4   -0.5   -0.4   0.0
     0.2    0.0   -0.2   -0.3   -0.2   0.2
     0.4    0.2    0.0   -0.1    0.0   0.4
     0.5    0.3    0.1    0.0    0.1   0.5
     0.4    0.2    0.0   -0.1    0.0   0.4
     0.0   -0.2   -0.4   -0.5   -0.4   0.0

Upvotes: 0

Views: 316

Answers (2)

Sotos
Sotos

Reputation: 51582

Here are a couple of options,

sapply(a, function(i) i-a)

matrix(Reduce(`-`, expand.grid(a,a)), ncol = length(a))

Upvotes: 2

user2974951
user2974951

Reputation: 10375

Using outer

a <- c(17.4, 17.2, 17.0, 16.9, 17.0, 17.4)
t(outer(a,a,`-`))

     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]  0.0 -0.2 -0.4 -0.5 -0.4  0.0
[2,]  0.2  0.0 -0.2 -0.3 -0.2  0.2
[3,]  0.4  0.2  0.0 -0.1  0.0  0.4
[4,]  0.5  0.3  0.1  0.0  0.1  0.5
[5,]  0.4  0.2  0.0 -0.1  0.0  0.4
[6,]  0.0 -0.2 -0.4 -0.5 -0.4  0.0

Upvotes: 4

Related Questions