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
>Solution :
Here are a couple of options,
sapply(a, function(i) i-a)
matrix(Reduce(`-`, expand.grid(a,a)), ncol = length(a))