Played with runtimes for discretize() a bit more. Size of x_grid only mildly important. When xval is 1000 points or less, the max() is faster, but from about 100000 points or more on xval discretize() is faster. In between it can vary.
VFI Toolkit essentially does this operation of putting points onto grid in two places. Once ‘CreateaprimeFn’ (in various versions), which can be just a few hundred points for xi. Once ‘CreateaprimePolicy’ (in various versions) where xi is going to be millions of points. So I changed all the ‘CreateaprimePolicy’ to discretize(). Put an if-statement in the ‘CreateaprimeFn’ and choose which based on if xval has lots of points (runtimes suggest the if-statement slowdown is tiny, and avoiding being substantially wrong on which of max() and discretize() to use is worth the if-statement). [The ‘CreateaprimeFn’ are used in value function iteration, whereas ‘CreateaprimePolicy’ is in agent distribution iteration.]
That said, if you just always use discretize() the maximum potential losses in runtime are only around 10^(-3) or 10^(-4) seconds [per time you call it]. So if I wanted an easy option I would go with just using discretize() all the time. [lost runtime from using max() when discretize() is better can be hundreths of a second, even tenths of a second if xval is large]
[My exact if-statement is that numel(xval)*numel(x_grid)<1000000, then use max(), else use discretize(). Seems to always get within about 10% of the best possible runtimes.]
The comparison was
[~,indx]=max(xval>x_grid); % upper grid point
indx=indx-1; % lower grid point
indx(indx==1);
indx(xval<x_grid(1))=1;
indx(xval>x_grid(end))=n_x-1;
Versus,
indx=discretize(xval,x_grid);
indx(xval<x_grid(1))=1;
indx(xval>x_grid(end))=n_x-1;