1 ## Copyright (C) 2010 Soren Hauberg
3 ## This program is free software; you can redistribute it and/or modify
4 ## it under the terms of the GNU General Public License as published by
5 ## the Free Software Foundation; either version 3, or (at your option)
8 ## This program is distributed in the hope that it will be useful, but
9 ## WITHOUT ANY WARRANTY; without even the implied warranty of
10 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 ## General Public License for more details.
13 ## You should have received a copy of the GNU General Public License
14 ## along with this file. If not, see <http://www.gnu.org/licenses/>.
17 ## @deftypefn {Function File} mtimes (@var{KP})
18 ## XXX: Write documentation
21 function retval = mtimes (M1, M2)
26 ## This seems to be what happens for full and sparse matrices, so we copy this behaviour
31 if (!ismatrix (M1) || !ismatrix (M2))
32 error ("mtimes: input arguments must be matrices");
35 if (columns (M1) != rows (M2))
36 error ("mtimes: nonconformant arguments (op1 is %dx%d, op2 is %dx%d)",
37 rows (M1), columns (M1), rows (M2), columns (M2));
40 ## Take action depending on input types
41 M1_is_KP = isa (M1, "kronprod");
42 M2_is_KP = isa (M2, "kronprod");
44 if (M1_is_KP && M2_is_KP) # Product of Kronecker Products
45 ## Check if the size match such that the result is a Kronecker Product
46 if (columns (M1.A) == rows (M2.A) && columns (M1.B) == rows (M2.B))
47 retval = kronprod (M1.A * M2.A, M1.B * M2.B);
49 ## Form the full matrix of the smallest matrix and use that to compute the
51 ## XXX: Can we do something smarter here?
55 retval = full (M1) * M2;
57 retval = M1 * full (M2);
61 elseif (M1_is_KP && isscalar (M2)) # Product of Kronecker Product and scalar
62 if (numel (M1.A) < numel (M1.B))
63 retval = kronprod (M2 * M1.A, M1.B);
65 retval = kronprod (M1.A, M2 * M1.B);
68 elseif (M1_is_KP && ismatrix (M2)) # Product of Kronecker Product and Matrix
69 retval = zeros (rows (M1), columns (M2));
70 for n = 1:columns (M2)
71 M = reshape (M2 (:, n), [columns(M1.B), columns(M1.A)]);
72 retval (:, n) = vec (M1.B * M * M1.A');
75 elseif (isscalar (M1) && M2_is_KP) # Product of scalar and Kronecker Product
76 if (numel (M2.A) < numel (M2.B))
77 retval = kronprod (M1 * M2.A, M2.B);
79 retval = kronprod (M2.A, M1 * M2.B);
82 elseif (ismatrix (M1) && M2_is_KP) # Product of Matrix and Kronecker Product
83 retval = zeros (rows (M1), columns (M2));
85 M = reshape (M1 (n, :), [rows(M2.B), rows(M2.A)]);
86 retval (n, :) = vec (M2.B' * M * M2.A);
90 error ("mtimes: internal error for 'kronprod'");