function [intensity_regrid] = regrid(x, y, intensity, targetSize)

xx = x;
yy = y;

% find the minimum and maximum data values
minX = min(xx);
maxX = max(xx);
minY = min(yy);
maxY = max(yy);

% calculate the indices of the boxes the data points fall into
xxBin = round( (xx-minX)/(maxX-minX)*(targetSize(1)-1) ) +1;
yyBin = round( (yy-minY)/(maxY-minY)*(targetSize(2)-1) ) +1;

% remove NaN values
L = isnan(intensity);
intensity(L) = [];
xxBin(L) = [];
yyBin(L) = [];

if numel(xxBin) == numel(intensity)
    % map by using accumarray, take the mean of each bin
    intensity_regrid = accumarray([xxBin(:),yyBin(:)],intensity,targetSize)./accumarray([xxBin(:),yyBin(:)],1,targetSize);
else
    msgbox(['Regridding (during the conversion from pixel to q space) not possible.', char(10), 'Most likely reasons: You have loaded a scaled image and/or selected the wrong beamline.', char(10), 'Use original measurement files and make sure you have selected the correct beamline.'], 'Regridding not possible', 'modal');
end

end

