Home > Software engineering >  Make matrix by subtracting each element of vector from other element of it
Make matrix by subtracting each element of vector from other element of it

Time:11-30

suppose I have a vector a <- c(17.4, 17.2, 17.0, 16.9, 17.0, 17.4) How to make 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 first element store the result in first row of the matrix A, then subtract all elements from the second element in the vector a store it in the second row of matrix a and so on till the end element of vector a. 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

CodePudding user response:

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

CodePudding user response:

Here are a couple of options,

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

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