title: How to multiply each element of a 2d array by each of its neighbours, and then sum them over the whole array
body: <p>I am incredibly stuck on a problem for my university. I am attempting to simulate a lattice, and part of this is to find the total energy, which is done by multiplying each element of an n*n array by its four neighbours, and summing these over the whole array. </p>
  
  <p>I honestly have no idea of where to start with this and am incredibly stuck. Could anyone give me a hand? </p>
  
  <p>This is the code i have up to this point.</p>
  
  <pre><code>#defining the number of rows and columns in the lattice array
  n&lt;-20
  #creating a sample of n^2 values of either -1 or 1
  x&lt;-sample(seq(-1,1,by=2), n*n, replace=T)
  #plotting an n*n array with each point randomised to 1 or -1
  S&lt;-array(x, dim=c(n,n))
  #printing the array
  print(S)
  #Plotting the Lattice, red points are 1, white is -1
  image(1:20,1:20,S,zlim=c(-1,1),ylab="Column Number",xlab="Row Number")
  #Defining the average magnetisation
  Mag&lt;-(1/(n*n))*sum(S)
  #Printing the average magnetisation
  print(Mag)
  </code></pre>