latencyfit_jp.m 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. function [lat,coeff] = latencyfit_jp(y,t,fig)
  2. %TIME IN MILLISECONDS!
  3. %Must be col vectors
  4. % ----------------------------------------------
  5. % clear all;
  6. %
  7. % generate some example data
  8. % coeff = [0.004 0.11 0.07 80 14]; % typical values of V1 modulation
  9. % coeff = [0.04 0.2 1.3 50 7]; % typical values of V1 PSTH
  10. %
  11. % a = coeff(1);
  12. % c = coeff(2);
  13. % d = coeff(3);
  14. % m = coeff(4);
  15. % s = coeff(5);
  16. %
  17. % t = [-300:1:600]';
  18. % y = d * exp(m*a+0.5*s^2*a^2-a.*t).*normcdf(t,m+s^2*a,s)+c.*normcdf(t,m,s);
  19. %
  20. % y = y+0.1*randn(size(y)); % add some noise
  21. %
  22. % figure;plot(t,y,'b');legend({'data'});
  23. % make educated guess for starting values (instead of these you can also
  24. % use a list of starting values, for example based on previous data,
  25. % and loop over these and pick the one with the best fit)
  26. [Y,I] = max(y);
  27. m = t(I);
  28. st_=[0.004 Y/2 Y/2 m 200];
  29. % use curve tracing toolbox
  30. ft_ = fittype('d * exp(m*a+0.5*s^2*a^2-a.*t).*normcdf(t,m+s^2*a,s)+c.*normcdf(t,m,s);',...
  31. 'dependent',{'r'},'independent',{'t'},...
  32. 'coefficients',{'a', 'c', 'd', 'm', 's'});
  33. fo_ = fitoptions('method','NonlinearLeastSquares','MaxFunEvals',1000,'Lower',[0,0,0,0,0]);
  34. set(fo_,'Startpoint',st_);
  35. try
  36. [cfun,gof,output] = fit(t,y,ft_,fo_);
  37. catch
  38. %Fit went wrong
  39. lat = NaN;
  40. coeff = NaN(1,5);
  41. return
  42. end
  43. [coeff]=coeffvalues(cfun);
  44. if 0 % use optimization toolbox instead
  45. % r = d * exp(m*a+0.5*s^2*a^2-a.*t).*normcdf(t,m+s^2*a,s)+c.*normcdf(t,m,s);
  46. predicted = @(a,tdata) a(3) * exp(a(4)*a(1)+0.5*a(5)^2*a(1)^2-a(1).*t).*normcdf(t,a(4)+a(5)^2*a(1),a(5))+a(2).*normcdf(t,a(4),a(5));
  47. options = optimset('MaxFunEvals',2000);
  48. x0=st_;
  49. lb=[0,0,0,0,0];
  50. ub=[Inf,Inf,Inf,Inf,Inf];
  51. [coeff]=lsqcurvefit(predicted,x0,t,y,lb,ub,options);
  52. end
  53. % coefficients of fit
  54. a = coeff(1);
  55. c = coeff(2);
  56. d = coeff(3);
  57. m = coeff(4);
  58. s = coeff(5);
  59. yf = d * exp(m*a+0.5*s^2*a^2-a.*t).*normcdf(t,m+s^2*a,s)+c.*normcdf(t,m,s);
  60. [mf,mfix] = max(yf);
  61. ixs = [1:mfix]; % only search before max peak
  62. [l33,l33ix]=min(abs(yf(ixs)-mf*0.33));
  63. lat = t(l33ix);
  64. if fig
  65. figure; hold on;
  66. plot(t,y,'b',t,yf,'r');
  67. legend({'data','fit'});
  68. plot([t(l33ix),t(l33ix)],get(gca,'YLim')); % point where 33% of max response reached
  69. end