demo.m 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. close all; clear all; clc;
  2. T=150*1e-3; %[s] duration of post-stimulus time window
  3. Fs=1e3; %[Hz] sampling frequency
  4. Ncs=4; % Number of channels
  5. Nts=T*Fs; % Number of timepoints
  6. ts=linspace(0,T,Nts); %[s] time points after stimulus
  7. ft = @(p,t)(p(5)*exp(p(1)*p(3)+0.5*p(2)^2*p(3)^2-p(3)*t)...
  8. .*normcdf(t,p(1)+p(2)^2*p(3),p(2))+p(4)*normcdf(t,p(1),p(2)));
  9. % Generate some synthetic data with random latency ranging 20÷70 [ms]
  10. mu=zeros(1,Ncs); lt=zeros(1,Ncs); xt=zeros(Ncs,Nts);
  11. for ch=1:Ncs
  12. mu(ch)=(20+randi(50,1));
  13. xt(ch,:)=feval(ft,[mu(ch) 10 3 0.1 6],ts*1e3);
  14. lt(ch)=ts(find(xt(ch,:)>=1/3*max(xt(ch,:)),1,'first'));
  15. end
  16. yt=xt+.01*randn(Ncs,Nts);
  17. % Get Latencies
  18. [latTimes0, lsqCurveTimes0, lsqFittedCurve0, lsqFittedParam0, lsqCurveFitErr0] = computeLatencies(xt,ts*1e3,10);
  19. [latTimes, lsqCurveTimes, lsqFittedCurve, lsqFittedParam, lsqCurveFitErr] = computeLatencies(yt,ts*1e3,10);
  20. %% Plot results
  21. % multi-line plot offset
  22. ploffs0=repmat((1:Ncs)'*max(yt(:)),1,Nts);
  23. ploffs=repmat((1:Ncs)'*max(yt(:)),1,length(lsqCurveTimes));
  24. figure(); hold on
  25. plot(-inf,-inf,'b-'); plot(-inf,-inf,'k-'); plot(-inf,-inf,'r-');
  26. plot(-inf,-inf,'bo'); plot(-inf,-inf,'ko'); plot(-inf,-inf,'ro');
  27. plot(-inf,-inf,'bx'); plot(-inf,-inf,'kx'); plot(-inf,-inf,'rx');
  28. plot(ts*1e3,xt+ploffs0,'b-'); hold on;
  29. plot(ts*1e3,yt+ploffs0,'k-'); hold on;
  30. plot(lsqCurveTimes,lsqFittedCurve+ploffs,'r-'); hold on;
  31. plot(lt*1e3,ploffs0(:,1),'bo');
  32. plot(latTimes0,ploffs0(:,1),'ko');
  33. plot(latTimes,ploffs0(:,1),'ro');
  34. plot(mu,ploffs0(:,1),'bx');
  35. plot(lsqFittedParam0(:,1),ploffs0(:,1),'kx');
  36. plot(lsqFittedParam(:,1),ploffs0(:,1),'rx');
  37. xlabel('time (ms)');
  38. ylabel('channels'); set(gca,'YTick',[]);
  39. hl=legend('x(t) sample signal','y(t)=x(t)+noise','f(t) fitted function','true latency',...
  40. 'latency fit(x)','latency fit(y)','true mean','mean fit(x)','mean fit(y)');
  41. hl.EdgeColor='none'; hl.Location='southeast';