function [ym,ysum,ns] = condexp(y,x,xrg)
	% [ym,ys] = condexp(y,x,xrg)
	% Computes ym(ii) = mean(y(x>=xrg(ii) & x < xrg(ii+1)) for every ii
	% additionally computes
	%          ys(ii) = sum(y(x>=xrg(ii) & x < xrg(ii+1)) for every ii
	% and      ns(ii) = sum(x>=xrg(ii) & x < xrg(ii+1))
	%
	% uses a fast algorithm based on the MATLAB builtin accumarray
	%
	% support for conditionally averaging vector, matrix or n-dimensional
	% data 

	assert(all(size(y) == size(x)))
	n_edges			= length(xrg);
	n_bins			= n_edges-1;
	[~,bins]		= histc(x(:),xrg(:)');

	ok				= bins > 0 & bins < n_edges;
	n_ok			= sum(ok);

	ns				= accumarray(bins(ok), ones(n_ok,1), [n_bins 1]);
	ysum			= accumarray(bins(ok), y(ok)       , [n_bins 1]);
	ym				= ysum ./ ns;
end