function p = pixelfrac(s, coord)
%SAXS/PIXELFRAC Return fractional pixel coordinates for given x,y coordinates.
%   P = PIXELFRAC(S, [X Y]) returns pixel coordinates [COLUMN, ROW]
%   of the given axis coordinates in the SAXS image object S.
%   If X or Y lies outside the image, a NaN is returned for the
%   corresponding column or row in P.
%   Multiple rows of [X Y] return multiple rows in P.

[nrows ncols] = size(s.pixels);
p(:, 1) = pixel(ncols, s.xaxis, coord(:, 1));
p(:, 2) = pixel(nrows, s.yaxis, coord(:, 2));



function pixelnum = pixel(npixels, axis, axisvalue)
%PIXEL Find fraction pixel number for an axis value.
if isempty(axis)  % no axis, pixel numbers are axis coordinates
    pixelnum = axisvalue;
    pixelnum(pixelnum < 1) = nan;
    pixelnum(pixelnum > npixels) = nan;
else  % interpolate nearest pixel number
    first = axis(1);
    last = axis(2);
    step = (last - first) / (npixels - 1);
    pixelnum = interp1(first : step : last, 1 : npixels, axisvalue, 'linear','extrap');
end
