Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Here are a couple of options,

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

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading