I'm a Mathematica novice here. I'm trying to execute the following code to add random 1's into a zero matrix, repeat this many times, and then bin/histogram the number of nearest neighbor 1s. Can anyone help me out with what I need to do to transform my list so that bincounts will play nicely?

(*clear global variables*)
n = 10;  
(*set number of diluent elements*)
    b = SparseArray[{1, 1} -> 0, {100, 1},0]; 
    (*generate zero matrix*)
    a = RandomSample[Range[100],  n]; 
    (*select random sites to add elements *)
    Do[b[[a[[i]]]] = 1, {i, n}]; 
    (*insert elements*)
    e[i] = b; 
    (*generate iterated variable to record each run*) 
(*loop i times*)
f = Table[e[i], {i,1,50}];
(*generate list from iterated variable*)
Do[g[j, i] = f[[j, i]] + f[[j, i + 1]], {j, 50}, {i, 99}];
(*sum nearest neighbors and loop over data set*)
h = Table[g[j, i], {i, 1, 99}, {j, 1, 50}] ; 
(*create an indexed list variable*)
BinCounts[h, {0, 3, 1}]

Where Bincounts returns the error: "BinCounts::vectmat: The first argument is expected to be a vector or matrix"

  • 1
    $\begingroup$ a vector is one-dimensional array object. if you want BinCount working just do this: BinCount[Flatten[h],{0, 3, 1}] $\endgroup$
    – Stefan
    Commented Jun 28, 2013 at 17:33
  • 1
    $\begingroup$ BinCounts doesn't work because h isn't a list or a matrix. Instead of the above code, you code use h = RandomInteger[{0, 1}, {100, 100}] to generate a 100x100 matrix of 0's and 1's. Furthermore, I don't think you'll want to use BinCounts to count the number of 1' that are adjacent (assuming this is what you want; your question isn't quite clear). $\endgroup$ Commented Jun 28, 2013 at 18:07

1 Answer 1


Here is a straightforward way to count the number of nearest neighbor ones in a matrix of zeros.

h = RandomChoice[{0.8, 0.2} -> {0, 1}, {10, 10}];
Total[Sign[DeleteSmallComponents[MorphologicalComponents[h], 1]], 2]

The h matrix is a 10 by 10 matrix of ones and zeros (change the 10s to change the size) where about 20% of the elements are ones and 80% are zeros (change the probabilities {0.8,0.2} to the desired percentages). The next line calculates how many ones there are in h after removing all those that are disconnected. This is equal to the number of ones in h that are touching each other. This version assumes that "nearest neighbor 1s" means any neighbor in the left, right, up, down, or diagonal direction. If a more restricted use of the word "neighbor" is desired, this is also possible using the option CornerNeighbors->False.

For example, when h looks like this

enter image description here

the number of components that are adjacent to any one is 12 (of the 15 ones, 3 are disconnected and so are removed by DeleteSmallCompoenents).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.