 <p>You got the entire logic correct, except one minor flaw. You have <code>idxR</code> as a logical matrix. Hence <code>colonies</code> is a logical matrix too. Therefore, you get the expected output till the second-last line. Problem occurs on the last line, when you try to assign an array of numbers in which each number is greater than 1 (<code>colonies(colonies==1).*ret;</code>) to a logical matrix.</p> <p>Elements greater than 1 are clipped to one and thus you see only zeros and ones. There is a simple workaround. Change the first line to </p> <pre><code>colonies = double(idxR); </code></pre> <p>P.S. The answer was right in front of you, you just didn't spot it. You had written: </p> <blockquote> <p>I tried this code in a new file and assigned a matrix with random ones and zeros to idxR and then it seems to work.</p> </blockquote> <p>The <code>idxR</code> matrix must have been of double datatype, if you used <code>randi</code>.</p>