-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathspm_diag.m
44 lines (35 loc) · 1.26 KB
/
spm_diag.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function D = spm_diag(varargin)
% Diagonal matrices and diagonals of a matrix
%
% SPM_DIAG generalises the function "diag" to also work with cell arrays.
% See DIAG's help for syntax.
%__________________________________________________________________________
% Copyright (C) 2009 Wellcome Trust Centre for Neuroimaging
% Guillaume Flandin
% $Id: spm_diag.m 7809 2020-03-31 11:55:09Z karl $
# SPDX-License-Identifier: GPL-2.0
try
X = varargin{1};
catch
error('Not enough input arguments.');
end
% use built-in diag for most data types
%--------------------------------------------------------------------------
if ~iscell(X)
D = diag(varargin{:});
% or use the following for cell arrays
%--------------------------------------------------------------------------
else
if nargin < 2, K = 0; else, K = varargin{2}; end
[m,n] = size(X);
% return the cell array whose K-th diagonal is X
%----------------------------------------------------------------------
if any([m n] == 1)
D = cell(max(m,n) + abs(K));
D(logical(diag(ones(1,max(m,n)),K))) = X;
% return the K-th diagonal of X
%----------------------------------------------------------------------
else
D = X(logical(diag(ones(1,max(m,n)-abs(K)),K)));
end
end