K = GauK(q1+1-length(selx):q1,q1+1-length(sely):q1);
While this tricks works well on the left side of the image, it doesn't work on its right side.
Imagine you are 2 pixels left to the boundary on the right side.
The selection of the pixel would be from far left until the center + 2 on the right of the center of the Gaussian.
Yet the selection of the weights from the Gaussian would be 2 left to the peak, the peak and then down till the boundary.
Multiplying them means multiplying them in the wrong order which creates the wrong weights.