There is a rather elegant way to do this. It relies on something called the tensor product. The tensor product (⊗ in math) is an operation which takes two matrices and returns a matrix whose shape is the product of their shapes by replacing each number in the matrix on the left with an entire copy of the matrix on the right, multiplied by that number. It's very easy to write in J:
tp =: ,./^:2 @: (*/) We will also need the identity matrix I given by =@i. and the adjacency matrix M for a simple path A--B--C--... of the appropriate length, which is given by (1 = |@-/~@:i.) . The matrix for a large square network of the form you are considering is the sum of two tensor products: first I⊗M, which corresponds to staying in the same row and moving to either side, then M⊗I, which corresponds to moving up or down. Then we just add these together. adjmat =: =@i. (tp +. tp~) 1 = |@-/~@:i. If you want a matrix for a nonsquare network, with side lengths m and n, then the matrix is I_m⊗M_n + M_m⊗I_n . We can do this with I =: i.@:= M =: 1 = |@-/~@:i. adjmat2 =: (I@[ tp M@]) + (M@[ tp I@]) Marshall On Sun, Feb 24, 2013 at 01:21:53PM +0100, alessandro codenotti wrote: > > I had this network problem to solve and i wrote the code to do it, everything > was fine until i noticed i wasn't able to compute the adjacency matric to > work on! > > the network is a square network where every node is connected to is > neighbours, for the 3x3 case it looks like this: > > A----B----C > | | | > D----E----F > | | | > G----H----I > > where A,B,C...,I are the 9 nodes and the corresponding adjacency matrix can > be easily obtained by hand, however i have to work on different networks of > different sizes, but they are all squares and all connected like that. > My question then is more a maths question than a programming one (well, is > there any J programmer that doesn't love maths?), if i need the adjacency > matrich of such networks, is there an easy way to find it knowing the > propertiese of the network given above? and how can i do it in J? > > thank in advice for the help! > > > ---------------------------------------------------------------------- > For information about J forums see http://www.jsoftware.com/forums.htm ---------------------------------------------------------------------- For information about J forums see http://www.jsoftware.com/forums.htm
