Computing the distance and weight matrix of a graph I would like to create an igraph object. First, I set up the size of igraph object — n, m, then create a random matrix. As a result matrix B will be filled. Matrix B is the adjacency matrix for the igraph object. Inside for-loops I compute the distance d (scalar) and the weight matrix W. I would like to improve the perfomance of calculation. I think it is possible because I have used 4 for-loops in my code:

n &lt;- 6 
m &lt;- 7 

mat &lt;- matrix(sample(0:255, n*m, replace=T), nrow = n, ncol = m)
R &lt;- 2

a &lt;- 1 
b &lt;- 1 

d &lt;- 0 
e &lt;- 0 
g &lt;- 0 

W &lt;- matrix(0, n, m) 
B &lt;- matrix(0, n*m, n*m)

for (i in 1:n){
for (j in 1:m){
  for (i0 in 1:n){
  for (j0 in 1:m){
            d &lt;- ((i0 - i)^2+(j0 - j)^2)^(1/2) 
            e &lt;- ifelse(d &lt;= R, 1, 0)
            g &lt;- abs(mat[i,j] - mat[i0,j0])
            W[i0,j0] &lt;- e * ((a*g)^2 + (b*d)^2)^(1/2)
  } # for i0
  } # for j0
  B[m * (i-1)+j,] &lt;- c(t(W)) 

} #for_j
} #for_i


Could anyone please give me an idea how to rewrite the above code with fewer or no for-loops?
Here is how you would do it with no for loops. The dist() function computes the distance between every pair of rows of a matrix. So you have to apply it to two matrices:


the matrix C where each row contains the i and j coordinates of each vertex.
the matrix matrix(M, ncol = 1) where each row contains the value at a vertex.




M &lt;- t(mat)
C &lt;- cbind(c(row(M)), c(col(M)))
D &lt;- as.matrix(dist(C, method = "euclidean"))
E &lt;- as.numeric(D &lt;= R)
G &lt;- as.matrix(dist(matrix(M, ncol = 1), method = "manhattan"))
B &lt;- E * ((a * G) ^ 2 + (b * D) ^ 2) ^ (1 / 2)


Note that in R, matrices are stored using "Column Major", i.e. column by column. So it would be more natural to pick that the second row/col in B corresponds to the item at row 2 and col 1 in mat. You chose the opposite (row 1 col 2) which forced me to start my code with M &lt;- t(mat). If you want to pick the more natural approach as I suggest, just replace that first line with M &lt;- mat.