Computing the distance and weight matrix of a graph
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.