spm_diag.m 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. function D = spm_diag(varargin)
  2. % Diagonal matrices and diagonals of a matrix
  3. %
  4. % SPM_DIAG generalises the function "diag" to also work with cell arrays.
  5. % See DIAG's help for syntax.
  6. %__________________________________________________________________________
  7. % Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging
  8. % Guillaume Flandin
  9. % $Id: spm_diag.m 4310 2011-04-18 16:07:35Z guillaume $
  10. try
  11. X = varargin{1};
  12. catch
  13. error('Not enough input arguments.');
  14. end
  15. % use built-in diag for most data types
  16. %--------------------------------------------------------------------------
  17. if ~iscell(X)
  18. D = diag(varargin{:});
  19. % or use the following for cell arrays
  20. %--------------------------------------------------------------------------
  21. else
  22. try, K = varargin{2}; catch, K = 0; end
  23. [m,n] = size(X);
  24. % return the cell array whose K-th diagonal is X
  25. %----------------------------------------------------------------------
  26. if any([m n] == 1)
  27. D = cell(max(m,n) + abs(K));
  28. D(logical(diag(ones(1,max(m,n)),K))) = X;
  29. % return the K-th diagonal of X
  30. %----------------------------------------------------------------------
  31. else
  32. D = X(logical(diag(ones(1,max(m,n)-abs(K)),K)));
  33. end
  34. end