function patchMedians = computePatchMedian(patches)
    %compute the median image for a collection of patches
    patchMedians.patchNx = medianNaNFiltered(patches.patchNx, patches.patchValid);
    patchMedians.patchNy = medianNaNFiltered(patches.patchNy, patches.patchValid);
    patchMedians.patchNz = medianNaNFiltered(patches.patchNz, patches.patchValid);
end

function maskedMedian = medianNaNFiltered(image, valid)
    %compute the median, ignore invalid values
    masked = image;
    masked(~valid) = NaN;
    maskedMedian = nanmedian(masked,3); 
end
