# Symmetrical matrix

#### leejayd

##### New Member
Hi,

I have a vector representing distances between cities.

I have an nxn matrix looking like :

Code:
                Manchester  Leeds London
Manchester
Leeds
London
I'm trying to get the distances loaded to the matrix but I only have distances in one direction so I need to transpose them to make a fully symmetrical matrix i.e

Code:
                Manchester  Leeds London
Manchester           0       20     200
Leeds               20        0     230
London              200      230    0
What's the easiest way to do this?

Last edited:

#### Dason

If you show us how you actually have your data loaded that would help

#### leejayd

##### New Member
In an int vector

cities<-c(0,20,200,20,0,230,200,230,0)

I can manipulate this as it's actually coming to me in json format (with lots of other gunk) with all city distances - I have to ignore half of them as the matrix must be symmetrical.

Last edited:

#### Dason

Is that what you actually have? I was under the impression you only had the distances one time. If that's really what you have then matrix(cities, 3, 3) should do the trick. But I'm guessing you misunderstood what I was asking for. In what form is the data coming to you in R? Can you give a sample of that?

#### leejayd

##### New Member
I realise I can use
Code:
matrix(cities, nrow=3, ncol=3)
but I can't assume the reverse distances will be same (data from google gives different distances depending on direction!)

#### Dason

If you can create half the matrix and the other half is 0s then just add the matrix to its transpose.

Code:
> x <- matrix(c(0, 1, 2, 0,0,3,0,0,0),3,3)
> x
[,1] [,2] [,3]
[1,]    0    0    0
[2,]    1    0    0
[3,]    2    3    0
> x+t(x)
[,1] [,2] [,3]
[1,]    0    1    2
[2,]    1    0    3
[3,]    2    3    0

#### leejayd

##### New Member
Perfect. Thanks so much. I had an idea there would be a function like this.