detrend4D.m 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. function output = detrend4D(functional4D_fn)
  2. % Function to detrend 4D fMRI data
  3. %
  4. % INPUT:
  5. % functional4D_fn - filename for 4D fMRI timeseries data (.nii)
  6. %
  7. % OUTPUT:
  8. % F_4D_detrended -
  9. %__________________________________________________________________________
  10. % Copyright (C) Stephan Heunis 2018
  11. % Get file info and convert 4D to 2D
  12. V = spm_vol(functional4D_fn);
  13. V1_3D = spm_read_vols(V(1));
  14. sizeV = size(V);
  15. [Ni, Nj, Nk] = size(V1_3D);
  16. Nt = sizeV(1);
  17. [x,y,z] = ind2sub(size(V1_3D),(1:Ni*Nj*Nk)');
  18. dataT = spm_get_data(V,[x y z]');
  19. F_2D = dataT';
  20. F_4D = reshape(F_2D, Ni, Nj, Nk, Nt);
  21. % Setup design matrix to include demeaned 1st, 2nd and 3rd order
  22. % polynomial and single mean regressors
  23. X_design = [ (1:Nt)' ((1:Nt).^2/(Nt^2))' ((1:Nt).^3/(Nt^3))'];
  24. X_design = X_design - mean(X_design);
  25. X_design = [X_design ones(Nt,1)];
  26. % GLM to get beta coefficients
  27. betas = X_design\F_2D';
  28. % Detrend data
  29. F_2D_detrended = F_2D' - X_design(:, 1:(end-1))*betas(1:(end-1), :);
  30. F_2D_detrended = F_2D_detrended';
  31. % 4D matrix
  32. F4D_detrended = reshape(F_2D_detrended, Ni, Nj, Nk, Nt);
  33. % Output
  34. output.F_2D_detrended = F_2D_detrended;
  35. output.F4D_detrended = F4D_detrended;