fitGaussian1.m 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. function fitOutputStruct = fitGaussian1(x, yArray, gaussianSign, varargin)
  2. % Fit one dimensional Gaussian to trial data or to many cells (ROIs).
  3. switch nargin
  4. case {1, 2, 3}
  5. dataStructure = 'cells';
  6. case 4
  7. dataStructure = varargin{1};
  8. end
  9. switch dataStructure
  10. case 'cells'
  11. case 'trials'
  12. originalArray = yArray;
  13. yArray = mean(yArray, 1);
  14. end
  15. if ~exist('gaussianSign', 'var') || isempty(gaussianSign) || gaussianSign == 0
  16. convexityProxy = approximateConvexity(yArray);
  17. else
  18. convexityProxy = gaussianSign * ones(1, size(yArray, 1));
  19. end
  20. fitOutputStruct(size(yArray, 1)).fit = nan;
  21. fitOutputStruct(size(yArray, 1)).gof = nan;
  22. fitOutputStruct(size(yArray, 1)).info = nan;
  23. for iRF = 1: size(yArray, 1)
  24. % x = (1 : numel(yArray(iRF, :)));
  25. % Idea: recover the smoothing filter through deconvolution to
  26. % deconvolve the fitted gaussian.
  27. % y = smoothdata(yArray(iRF, :), 'gaussian');
  28. y = (yArray(iRF, :));
  29. options = fitoptions('gauss1');
  30. options.Lower = [-10 1 1];
  31. options.Upper = [10 numel(y) - 1 numel(y)];
  32. if sign(convexityProxy) == 1
  33. options.Lower(1) = 0;
  34. [~, maxInd] = max(y);
  35. options.StartPoint = [max(y) maxInd 1];
  36. else
  37. options.Upper(1) = 0;
  38. [~, minInd] = min(y);
  39. options.StartPoint = [min(y) minInd 1];
  40. end
  41. switch dataStructure
  42. case 'cells'
  43. [curve, gof, output] = fit(x', y','gauss1', options);
  44. case 'trials'
  45. x = repelem(x, size(originalArray, 1));
  46. [curve, gof, output] = fit(x', ColumnVector(originalArray),'gauss1', options);
  47. end
  48. fitOutputStruct(iRF).fit = curve;
  49. fitOutputStruct(iRF).gof = gof;
  50. fitOutputStruct(iRF).info = output;
  51. end
  52. end
  53. function convexityProxy = approximateConvexity(yArray)
  54. % Approximate the sign of the curvature, by summing lowest to highest
  55. % values.
  56. firstDecile = @(x) quantile(x, 0.1, 2);
  57. lastDecile = @(x) quantile(x, 0.9, 2);
  58. % concavity = gradient(gradient(yArray));
  59. lowValInds = yArray <= firstDecile(yArray);
  60. highValInds = yArray >= lastDecile(yArray);
  61. lowSum = zeros(1, size(yArray, 1));
  62. highSum = zeros(1, size(yArray, 1));
  63. % Carefull with smoothing level since bars and noise have different spatial
  64. % sampling rates.
  65. for iRF = 1: size(yArray, 1)
  66. % x = (1 : numel(yArray(iRF, :)));
  67. % y = smoothdata(yArray(iRF, :), 'gaussian', 3);
  68. y = (yArray(iRF, :));
  69. lowSum(iRF) = sum(y(lowValInds(iRF, :)));
  70. highSum(iRF) = sum(y(highValInds(iRF, :)));
  71. end
  72. convexityProxy = lowSum + highSum;
  73. end