optimalBW05.m 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. function [Rout,BWmax,MSRout]=optimalBW05(Rstin,Tin)
  2. %Tbin is the window to run the optimal bin on, such as Tbin=start:step:end i.e. Tbin=-1:0.005:2
  3. %Tin the PETH duration
  4. %T0 is window w/ the smallest binsize
  5. %
  6. global Tbin
  7. BW=[0.01:0.005:1];
  8. NUMTRL=length(Rstin);PTH0=[];
  9. Bsize=Tbin(2)-Tbin(1);
  10. Rst_all=sort(cell2mat(Rstin'));
  11. T0=[Tbin(1)-Bsize:Bsize:Tbin(end)+Bsize];L0=length(Tbin)-2;
  12. R0=hist(Rst_all,T0)/(Bsize*NUMTRL);R0=R0(2:end-1);SST=sum((R0-mean(R0)).^2);
  13. if isempty(Rst_all)
  14. R0=R0';
  15. end
  16. AIC=[];
  17. for i=1:length(BW)
  18. T=[Tbin(1)-BW(i):BW(i):Tbin(end)+BW(i)];P=length(T)-2;PTH=[];
  19. PTH_all=hist(Rst_all,T)/(BW(i)*NUMTRL);
  20. lambda_est=interp1(T(2:end-1),PTH_all(2:end-1),T0(2:end-1),'nearest','extrap');
  21. SSE=sum((lambda_est-R0).^2);
  22. %AIC
  23. AIC(i)=L0*log(SSE/L0)+2*P;
  24. % AIC(i)=2*mean(lambda_est)/(NUMTRL*BW(i))-var(lambda_est)
  25. end
  26. AICF=filtfilt(0.1*ones(1,10),1,AIC);
  27. [qwe,Imin]=min(AICF);BWmax=BW(Imin);
  28. % figure(1);plot(BW,AIC);hold on;plot(BW,AICF,'r')
  29. % fprintf(1,'final BW %1.4f\n',BWmax);
  30. MSRout=AIC;
  31. Tn=[-BWmax/2:-BWmax:Tin(1)-BWmax]; Tp=[BWmax/2:BWmax:Tin(end)+BWmax];T=[Tn(end:-1:1),Tp];%making PSTH centered on zero
  32. %T=[T0(1)-BWmax:BWmax:T0(end)+BWmax];
  33. PTH_opt=hist(Rst_all,T)/(BWmax*NUMTRL);
  34. %Assigning the output
  35. Rout=interp1(T(2:end-1),PTH_opt(2:end-1),Tin,'nearest','extrap');