Extracts the diagonal elements of A. function diagX = cdiag(X) Returns the diagonal elements of A. The input A does not necessarily to be a square matrix. The function supports both numeric arrays and structs with fields real and imag. Note that diag currently does not support dlarrays and cdiag can be seen as a backup function. See also: manoptADhelp
0001 function diagX = cdiag(X) 0002 % Extracts the diagonal elements of A. 0003 % 0004 % function diagX = cdiag(X) 0005 % 0006 % Returns the diagonal elements of A. The input A does not necessarily 0007 % to be a square matrix. The function supports both numeric arrays and 0008 % structs with fields real and imag. Note that diag currently does 0009 % not support dlarrays and cdiag can be seen as a backup function. 0010 % 0011 % See also: manoptADhelp 0012 0013 % This file is part of Manopt: www.manopt.org. 0014 % Original author: Xiaowen Jiang, Aug. 31, 2021. 0015 % Contributors: Nicolas Boumal 0016 % Change log: 0017 0018 if iscstruct(X) 0019 assert(length(size(X.real)) == 2, 'Input should be a 2-D array') 0020 m = size(X.real,1); 0021 n = size(X.real,2); 0022 realX = X.real; 0023 imagX = X.imag; 0024 if n >= m 0025 diagX.real = realX(1:m+1:m^2); 0026 diagX.imag = imagx(1:m+1:m^2); 0027 else 0028 diagX.real = realX(1:m+1:m*n-m+n); 0029 diagX.imag = imagX(1:m+1:m*n-m+n); 0030 end 0031 0032 elseif isnumeric(X) 0033 assert(length(size(X)) == 2, 'Input should be a 2-D array') 0034 m = size(X,1); 0035 n = size(X,2); 0036 if n >= m 0037 diagX = X(1:m+1:m^2); 0038 else 0039 diagX = X(1:m+1:m*n-m+n); 0040 end 0041 0042 else 0043 ME = MException('cdiag:inputError', ... 0044 'Input does not have the expected format.'); 0045 throw(ME); 0046 end 0047 0048 end