Search code examples
graph-theoryadjacency-matrixparipari-gp

Writing a code for a path graph in Pari/GP


I am trying to write a matrix for the adjacency matrix of the path graph on n vertices in Pari. For sake of clarity, when I say the graph P_n, I mean the graph with n vertices and n-1 edges.

So far, I have managed to do this for specific cases:

path2=matrix(2,2,i,j);for(i=1,2-1,path2[i,i+1]=1);for(i=2,2,path2[i,i-1]=1);path2

path3=matrix(3,3,i,j);for(i=1,3-1,path3[i,i+1]=1);for(i=2,3,path3[i,i-1]=1);path3

etc.

However, I'd like a code where I can choose the length of the path. Something like path(n)=.... When I try this with the above code, I get the following:

path(n)=matrix(n,n,i,j);for(i=1,n-1,path(n)[i,i+1]=1);for(i=2,n,path(n)[i,i-1]=1);path(n)
  ***   expected character: ',' or ')' instead of: ...or(i=1,n-1,path(n)[i,i+1]
  ***   =1);for(i=2,n,path(n)
  ***   ^---------------------

I'm not sure if this would be the right way to write this up and I'm missing something subtle or if I should be doing something different for this. Any help would be greatly appreciated!


Solution

  • The easiest way to do what you are trying to accomplish is something like:

    path(n)={matrix(n,n,i,j,abs(i-j)==1)}
    

    The reason you are getting errors is that you seem to have a misunderstanding about variables and functions. A correct implementation of your code is:

    path(n)={my(adj=matrix(n,n,i,j)); for(i=1,n-1, adj[i,i+1]=1); for(i=2,n,adj[i,i-1]=1); adj}
    

    This defines a function called path. Inside this function a local variable called adj is declared, which the code then fills out. At the end of the function, adj is returned. Note the final expression in a function is what is returned - there is no need to use an explicit return statement.

    However, as my first suggestion shows, it is often easy to avoid a lot of code by using the functional capabilities of the language.