time | calls | line |
---|
| | 1 | function K = kron(A,B)
|
| | 2 | %KRON Kronecker tensor product.
|
| | 3 | % KRON(X,Y) is the Kronecker tensor product of X and Y.
|
| | 4 | % The result is a large matrix formed by taking all possible
|
| | 5 | % products between the elements of X and those of Y. For
|
| | 6 | % example, if X is 2 by 3, then KRON(X,Y) is
|
| | 7 | %
|
| | 8 | % [ X(1,1)*Y X(1,2)*Y X(1,3)*Y
|
| | 9 | % X(2,1)*Y X(2,2)*Y X(2,3)*Y ]
|
| | 10 | %
|
| | 11 | % If either X or Y is sparse, only nonzero elements are multiplied
|
| | 12 | % in the computation, and the result is sparse.
|
| | 13 | %
|
| | 14 | % Class support for inputs X,Y:
|
| | 15 | % float: double, single
|
| | 16 | % integers: uint8, int8, uint16, int16, uint32, int32, uint64, int64
|
| | 17 |
|
| | 18 | % Thanks to Bruno Luong for full matrices implementation.
|
| | 19 | % See license.txt for license information.
|
| | 20 | % Thanks to Paul Fackler and Jordan Rosenthal for previous versions.
|
| | 21 | % Copyright 1984-2013 The MathWorks, Inc.
|
| | 22 |
|
| 8 | 23 | if ~ismatrix(A) || ~ismatrix(B)
|
| | 24 | error(message('MATLAB:kron:TwoDInput'));
|
| | 25 | end
|
| | 26 |
|
| 8 | 27 | [ma,na] = size(A);
|
| 8 | 28 | [mb,nb] = size(B);
|
| | 29 |
|
| 8 | 30 | if ~issparse(A) && ~issparse(B)
|
| | 31 |
|
| | 32 | % Both inputs full, result is full.
|
| | 33 |
|
| 8 | 34 | A = reshape(A,[1 ma 1 na]);
|
| 8 | 35 | B = reshape(B,[mb 1 nb 1]);
|
0.01 | 8 | 36 | K = reshape(bsxfun(@times,A,B),[ma*mb na*nb]);
|
| | 37 |
|
| | 38 | else
|
| | 39 |
|
| | 40 | % At least one input is sparse, result is sparse.
|
| | 41 |
|
| | 42 | [ia,ja,sa] = find(A);
|
| | 43 | [ib,jb,sb] = find(B);
|
| | 44 | ia = ia(:); ja = ja(:); sa = sa(:);
|
| | 45 | ib = ib(:); jb = jb(:); sb = sb(:);
|
| | 46 | ik = bsxfun(@plus, mb*(ia-1).', ib);
|
| | 47 | jk = bsxfun(@plus, nb*(ja-1).', jb);
|
| | 48 | K = sparse(ik,jk,bsxfun(@times,sb,sa.'),ma*mb,na*nb);
|
| | 49 | end
|