function [newvec] = apply_median_filter(vec)
% Apply a median filter to vector VEC % % [NEWVEC] = APPLY_MEDIAN_FILTER(VEC) % % Replace each item with the median of itself and its two % neighbors. For the first and last item, simply take the % median of themselves and their only neighbor.
if ndims(vec)>2 error(‘Cannot feed in n-dimensional matrices’) end
if min(size(vec))~=1 error(‘VEC must be a vector’) end
nItems = length(vec);
% we need to create a second variable, since if we try % and do it all in place on VEC, you’ll be taking the % median of values that themselves may be medians… newvec = nan(size(vec));
for v=1:nItems % if it’s the first item, just take the median of the % 1st and 2nd if v==1 newvec(v) = median([vec(v) vec(v+1)]); continue end % if it’s the last item, just take the median of the % last and penultimate if v==nItems newvec(v) = median([vec(v-1) vec(v)]); continue end
% otherwise, take the median of the item, its successor % and predecessor newvec(v) = median([vec(v-1) vec(v) vec(v+1)]);
end % v
% if there are any NaNs remaining in NEWVEC, then we’ve % messed up if length(find(isnan(newvec))) error(‘Logic bug - NEWVEC hasn”t been created properly’) end
Home - Blog - Startups - Software - Research - Writing
Email me - updated 31 Dec 2012