I want to create a nxn symmetric matrix in python. Lets say n=9, then I want something like below:
array[[0,1,0,0,0,1,1,0,1],[1,0,1,1,1,0,0,0,0],[0,1,0,1,1,0,0,0,0]….].
I know how to do this by first creating a nun zeros matrix in python (np.zeros((9,9)) and then using a loop to populate it 1 and zeros. But I feel that is not a pythonic way. So was looking for an optimised way using loops would slow the code if the matrix is big.
Basically it's the adjacency matrix I am creating for an undirected graph. My follow-up question would be how to plot the graph for which one has an adjacency matrix. Any functions which plot undirected graph from adjacency matrix?
Please advise. I wanted to learn the best optimised/pythonic way of doing something in python rather than using traditional loops.
EDIT:
I used the following to create a edge list for a 30x30 adjacency matrix. But this edge list doesn't have pairs for each node in a cluster. If I start doing that the list would be huge. My graph below consequently doesn't have edges between each node in a cluster. How to automate this edge list so that I don't have to manually type all edge pairs. In the graph I want each node in a cluster to have an edge with other node in that cluster and only node 1 and 2 should have between cluster edge with node 16 and 17 of other cluster.
N=30
# Creating a matrix of zeros.
W=np.zeros((N,N))
# Mentioning the edges to start with. Thinking of a pair of 15 node cluster with two cluster connected by two pair of nodes.
edge=[[1,2],[1,3],[1,4],[1,5],[1,6],[1,7],[1,8],[1,9],[1,10],[1,11],[1,12],[1,13],[1,14],[1,15],
[16,17],[16,18],[16,19],[16,20],[16,21],[16,22],[16,23],[16,24],[16,25],[16,26],[16,27],[16,28],[16,29],[16,30],
[1,16],[2,17]]
# Function for creating adjacency matrix ,populating the zeros matrix with 1 and 0-signifying edges on a node.
def adjacencyMatrix():
"""This function creates an Adjacency Matrix from a edge set.
input-> set of edges to be connected
output-> Adjacency matrix (n,n)
"""
for first,second in edge:
W[first-1,second-1]=W[second-1][first-1]=1
Graph:


is_adjacent(source_node, target_node)-type function is necessary, but do you have, for example, aget_neighbors(source_node)-type function that would return a list of target_nodes that were adjacent? That could be used to speed things up.