1########################################################################
2##
3## Copyright (C) 1994-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 {} {} polyvalm (@var{c}, @var{x})
28## Evaluate a polynomial in the matrix sense.
29##
30## @code{polyvalm (@var{c}, @var{x})} will evaluate the polynomial in the
31## matrix sense, i.e., matrix multiplication is used instead of element by
32## element multiplication as used in @code{polyval}.
33##
34## The argument @var{x} must be a square matrix.
35## @seealso{polyval, roots, poly}
36## @end deftypefn
37
38function y = polyvalm (c, x)
39
40  if (nargin != 2)
41    print_usage ();
42  endif
43
44  if (! (isvector (c) || isempty (c)))
45    error ("polyvalm: first argument must be a vector");
46  endif
47
48  if (! issquare (x))
49    error ("polyvalm: second argument must be a square matrix");
50  endif
51
52  n = length (c);
53  if (n == 0)
54    y = zeros (rows (x), class (x));
55  else
56    id = eye (rows (x), class (x));
57    y = c(1) * id;
58    for i = 2:n
59      y = y * x + c(i) * id;
60    endfor
61  endif
62
63endfunction
64
65
66%!assert (! any (polyvalm ([], [1, 2; 3, 4]))(:))
67%!assert (polyvalm ([1, 2, 3, 4], [3, -4, 1; -2, 0, 2; -1, 4, -3]), [117, -124, 11; -70, 36, 38; -43, 92, -45])
68
69%!error <must be a square matrix> polyvalm ([1, 1, 1], [1, 2; 3, 4; 5, 6])
70