1######################################################################## 2## 3## Copyright (C) 1993-2021 The Octave Project Developers 4## 5## See the file COPYRIGHT.md in the top-level directory of this 6## distribution or <https://octave.org/copyright/>. 7## 8## This file is part of Octave. 9## 10## Octave is free software: you can redistribute it and/or modify it 11## under the terms of the GNU General Public License as published by 12## the Free Software Foundation, either version 3 of the License, or 13## (at your option) any later version. 14## 15## Octave is distributed in the hope that it will be useful, but 16## WITHOUT ANY WARRANTY; without even the implied warranty of 17## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18## GNU General Public License for more details. 19## 20## You should have received a copy of the GNU General Public License 21## along with Octave; see the file COPYING. If not, see 22## <https://www.gnu.org/licenses/>. 23## 24######################################################################## 25 26## -*- texinfo -*- 27## @deftypefn {} {} trace (@var{A}) 28## Compute the trace of @var{A}, the sum of the elements along the main 29## diagonal. 30## 31## The implementation is straightforward: @code{sum (diag (@var{A}))}. 32## @seealso{eig} 33## @end deftypefn 34 35function y = trace (A) 36 37 if (nargin != 1) 38 print_usage (); 39 endif 40 41 if (ndims (A) > 2) 42 error ("trace: only valid on 2-D objects"); 43 elseif (isempty (A)) 44 y = 0; 45 elseif (isvector (A)) 46 y = A(1); 47 else 48 y = sum (diag (A)); 49 endif 50 51endfunction 52 53 54%!assert (trace ([1, 2; 3, 4]), 5) 55%!assert (trace ([1, 2; 3, 4; 5, 6]), 5) 56%!assert (trace ([1, 3, 5; 2, 4, 6]), 5) 57%!assert (trace ([]), 0) 58%!assert (trace (rand (1,0)), 0) 59%!assert (trace ([3:10]), 3) 60 61%!error trace () 62%!error trace (1, 2) 63%!error <only valid on 2-D objects> trace (reshape (1:9,[1,3,3])) 64