Q:

Matlab, how to apply medfilt2 function on specific pixel locations

Is there a way if I want to apply medfilt2 function to the specific pixel locations rather than the whole image? The pixel locations can be represented using a binary image called IMask. 

A:

The lazy method is to just apply medfilt2 on the whole image and then copy the specific locations. E.g.
A = magic(10); % sample matrix
IMask = logical(randi([0 1],10)); % sample locations

B = medfilt2(A);
A(IMask) = B(IMask);

Not very elegant, but will do the job unless your matrix is gigantic and IMask is mostly false.

