function ind = VLocate(x,z)
% 
% Pre:
%   x   column n-vector with x(1) < x(2) <...< x(n).
%   z   column m-vector s.t. for each j, x(1)<=z(j)<=x(n)
%
% Post:
%   ind column m-vector s.t. x(ind(j)) <= z(j) <= x(ind(j)+1)
%       for each j=1:m
% This routine is vectorized and requires O((m+n)*log(m+n)) time.
% In contrast, Locate is nonvectorized and requires O(m*log n)
% time.  Thus, this routine is no worse asymptotically than Locate provided
% n <= m <= polynomial(n), but is probably usually better because
% of vectorization.
% Written by SV, 2/7/03

[n,t] = size(x);
if t ~= 1 
  error('x must be a column vec')
end

[m,t] = size(z);
if t ~= 1
  error('z must be a column vec')
end


if any(x(1:n-1)>=x(2:n))
  error('x array must be in strictly increasing order');
end

if any(z < x(1)) | any(z > x(n))
  error('z array entries must lie in [x(1),x(n)]')
end

% Set up a matrix for sorting.

sortmat = [x, ones(n,1), zeros(n,1); z, zeros(m,1), (1:m)'];

% Sort it
sortmat = sortrows(sortmat);

% Count up the cumulative number of 1's in the 
% 2nd column of the sorted matrix.  This
% is correct interval for the entries

c = cumsum(sortmat(:,2));

% Make a mask that has 1's in the rows of sortmat that
% correspond to z's.

zmask = ~logical(sortmat(:,2));

% Extract the entries of c associated with z's.

cz = c(zmask);

% Extract indices associated with z's from the sorted order.

indz = sortmat(zmask,3);

ind = zeros(m,1);
ind(indz) = cz;

% Some of the indices could end up equal to 0 in the case
% that a z is equal x(1).  Increase those inds.

ind(ind==0) = 1;



