Compute_similarity_matrix.m 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. function [Corr_WiNs,Corr] = Compute_similarity_matrix(AmpResp,AllSamples)
  2. %% This function calculates the similarity matrix which estimates the correlation between pairs
  3. %% of sounds after correction for trial to trial noise
  4. %% INPUT
  5. % AmpResp = the responses to be correlations : ROI * stim * trials
  6. % AllSamples = 1 (default) calculates all possible pairs of trials, 0
  7. % instead does this for a random 50 combiations which is a lot quicker
  8. %% OUTPUT
  9. % Corr : matrix containing the correlation matrix between trial pairs for all
  10. % combinations : permutations * sounds * sounds
  11. % Corr : similarity matrix : sounds * sounds
  12. %% intialize
  13. if not(exist('AllSamples'))
  14. AllSamples = 1;
  15. end
  16. % clean up NaN cells
  17. NaN_cells = find(isnan(sum(squeeze(nanmean(AmpResp,3)'))));
  18. AmpResp(NaN_cells,:,:) = [];
  19. disp([num2str(length(NaN_cells)) ' ROIs out of ' num2str(size(AmpResp,1)) 'excluded because they had NaNs'])
  20. % Not all data sets have all of the trials, get the maximum number of
  21. % trials shared across datasets
  22. maxgoodtrials = find(squeeze(sum(sum(isnan(AmpResp),1),2))==0,1,'last');
  23. disp([num2str(maxgoodtrials) ' trials without NaNs'])
  24. % Get the trial pairs
  25. AllTrialPairs = combnk(1:maxgoodtrials,2);
  26. if AllSamples
  27. % all the samples
  28. TrialPairsToUse = AllTrialPairs;
  29. else
  30. % a subset of trial pairs
  31. TrialPairsToUse = AllTrialPairs(randperm(size(AllTrialPairs,1),30),:);
  32. end
  33. %% Calculate correlation for all pairs
  34. for perm = 1:size(TrialPairsToUse,1)
  35. Corr_WiNs(perm,:,:) = corr((squeeze(AmpResp(:,:,TrialPairsToUse(perm,1)))),(squeeze(AmpResp(:,:,TrialPairsToUse(perm,2)))));
  36. end
  37. %% Calculate noise corrected correlation
  38. for k = 1:size(Corr_WiNs,2)
  39. for kk = 1:size(Corr_WiNs,2)
  40. if k == kk
  41. Corr(k,kk) = NaN;
  42. else
  43. XCorr = abs(squeeze(nanmean(Corr_WiNs(:,k,k),1)));
  44. YCorr = abs(squeeze(nanmean(Corr_WiNs(:,kk,kk),1)));
  45. XYCorr = squeeze(nanmean(Corr_WiNs(:,kk,k),1));
  46. Corr(kk,k) = XYCorr./(sqrt(XCorr*YCorr));
  47. end
  48. end
  49. end
  50. end