MATLAB: Keep only elements that appear multiple times

arraymatrixnumelremovereplace

Hey everyone, been banging my head against this for awhile and can't come up with something efficient.
I have a large matrix, roughly 1000×1000, and I want to discard all elements (or replace with 0) that don't appear in the matrix at least three times. Additionally, I'm trying to allow for an error range so that, say, 10.1 and 9.9 (some arbitrary interval) will count as "10" (but this is secondary to the original problem).
I'm guessing that my main issue is that rewriting/editing a matrix is computationally expensive. The only solution I came up with involved numel in a loop, which is dreadfully slow.
Thanks for looking, advice is appreciated!

Best Answer

Actually I didn't need to find the inverse of permutation p. The following is one step shorter:
[B,p] = sort(A(:));
t = [true;diff(B)~=0;true];
q = cumsum(t(1:end-1));
t = diff(find(t))<3;
A(p(t(q))) = 0;