spm_imatrix.m 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. function P = spm_imatrix(M)
  2. % Return the parameters for creating an affine transformation matrix
  3. % FORMAT P = spm_imatrix(M)
  4. % M - Affine transformation matrix
  5. % P - Parameters (see spm_matrix for definitions)
  6. %__________________________________________________________________________
  7. %
  8. % See also: spm_matrix.m
  9. %__________________________________________________________________________
  10. % Copyright (C) 1996-2011 Wellcome Trust Centre for Neuroimaging
  11. % John Ashburner & Stefan Kiebel
  12. % $Id: spm_imatrix.m 4414 2011-08-01 17:51:40Z guillaume $
  13. %-Translations and Zooms
  14. %--------------------------------------------------------------------------
  15. R = M(1:3,1:3);
  16. C = chol(R'*R);
  17. P = [M(1:3,4)' 0 0 0 diag(C)' 0 0 0];
  18. if det(R)<0, P(7)=-P(7); end % Fix for -ve determinants
  19. %-Shears
  20. %--------------------------------------------------------------------------
  21. C = diag(diag(C))\C;
  22. P(10:12) = C([4 7 8]);
  23. R0 = spm_matrix([0 0 0 0 0 0 P(7:12)]);
  24. R0 = R0(1:3,1:3);
  25. R1 = R/R0;
  26. %-This just leaves rotations in matrix R1
  27. %--------------------------------------------------------------------------
  28. %[ c5*c6, c5*s6, s5]
  29. %[-s4*s5*c6-c4*s6, -s4*s5*s6+c4*c6, s4*c5]
  30. %[-c4*s5*c6+s4*s6, -c4*s5*s6-s4*c6, c4*c5]
  31. % There may be slight rounding errors making x>1 or x<-1.
  32. rang = @(x) min(max(x, -1), 1);
  33. P(5) = asin(rang(R1(1,3)));
  34. if (abs(P(5))-pi/2)^2 < 1e-9
  35. P(4) = 0;
  36. P(6) = atan2(-rang(R1(2,1)), rang(-R1(3,1)/R1(1,3)));
  37. else
  38. c = cos(P(5));
  39. P(4) = atan2(rang(R1(2,3)/c), rang(R1(3,3)/c));
  40. P(6) = atan2(rang(R1(1,2)/c), rang(R1(1,1)/c));
  41. end