Step 1: go back and de-vectorize your in, making it a 2D array again.
Step 2: use temporary variables to process one row at a time, and afterwards
It looks to me as if for each row, the columns that are within the tolerance distance should be replaced with the row number, and the ones not within tolerance should stay 0. If you had a logical vector for the row, that would be equivalent to multiplying the vector by the row number.
To get the logical vector you could use pdist2(), or you could perform the equivalent code using bsxfun or the new implicit expansion facilities of R2016b or later.