binned.m 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. function [binc, mu, se, n, ytob]=binned(x,y, varargin)
  2. % [binc, mu, se, n]=binned(x,y,bin_e)
  3. % Takes a vector x and a vector y and returns mean and standard error of
  4. % values of y for bins of x.
  5. %
  6. % Input:
  7. % x 1xn vector of x values to bin
  8. % y 1xn vector of y values to average
  9. %
  10. % Optional Input:
  11. %
  12. % n_bins Optional # of bins. Default 10
  13. % bin_e Optional bin edges. Otherwise will return n_bins bins with equal # of samples from
  14. % min(x) to max(x)
  15. %
  16. % Output:
  17. % binc 1xm bin centers
  18. % mu 1xm The average value of y at that bin
  19. % se 1xm The standard error of y at that bin
  20. % n 1xm The number of values of y in this bin
  21. bin_e=[];
  22. plot_it=false;
  23. plot_fit='';
  24. plot_fit_x0=[0 1 0 10];
  25. n_bins=10;
  26. clr='k';
  27. func=@nanmean;
  28. utils.overridedefaults(who,varargin);
  29. x=x(:);
  30. y=y(:);
  31. ytob=nan+y;
  32. if isempty(bin_e)
  33. pbins=linspace(0,100,n_bins+1);
  34. bin_e=prctile(x,pbins);
  35. end
  36. binc=(bin_e(2:end)+bin_e(1:end-1))/2;
  37. mu=nan(size(binc));
  38. se=nan(size(binc));
  39. if all(y==0 | y==1 | isnan(y))
  40. binomial_data=true;
  41. else
  42. binomial_data=false;
  43. end
  44. [n,yx]=histc(x,bin_e);
  45. for nx=1:(numel(n)-1)
  46. tmp=func(y(yx==nx));
  47. if isempty(tmp)
  48. tmp=nan;
  49. end
  50. mu(nx)=tmp;
  51. ytob(yx==nx)=nx;
  52. if binomial_data
  53. [~,ci]=binofit(nansum(y(yx==nx)),sum(yx==nx));
  54. se(nx)=max(abs(mu(nx)-ci));
  55. % this is bad for low n.
  56. else
  57. se(nx)=stats.nanstderr(y(yx==nx));
  58. end
  59. end
  60. n=n(1:end-1);
  61. if plot_it
  62. draw.errorplot(gca,binc, mu, se,'Marker','o','Color',clr);
  63. if ~isempty(plot_fit)
  64. beta=nlinfit(x,y,plot_fit,plot_fit_x0);
  65. xx=linspace(binc(1),binc(end),1000);
  66. yy=plot_fit(beta,xx);
  67. hold on;
  68. plot(xx,yy,'-','Color',clr);
  69. end
  70. if binomial_data
  71. ylim([0 1]);
  72. end
  73. end