5551
|
1 ## Copyright (C) 2000 Daniel Calvelo |
|
2 ## |
|
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 2 of the License, or |
|
6 ## (at your option) any later version. |
|
7 ## |
|
8 ## This program is distributed in the hope that it will be useful, |
|
9 ## but WITHOUT ANY WARRANTY; without even the implied warranty of |
|
10 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
|
11 ## GNU General Public License for more details. |
|
12 ## |
|
13 ## You should have received a copy of the GNU General Public License |
|
14 ## along with this program; if not, write to the Free Software |
|
15 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
|
16 |
|
17 ## -*- texinfo -*- |
|
18 ## @deftypefn {Function File} {} blkdiag (@var{a}, @var{b}, @var{c}, ...) |
|
19 ## Build a block diagonal matrix from @var{a}, @var{b}, @var{c}, ... . |
|
20 ## All the arguments must be numeric and are two-dimensional matrices or |
|
21 ## scalars. |
|
22 ## @end deftypefn |
|
23 ## |
|
24 ## @seealso{diag, horzcat, vertcat} |
|
25 |
|
26 ## Author: Daniel Calvelo |
|
27 ## Modified by: William Poetra Yoga Hadisoeseno |
|
28 |
|
29 function retval = blkdiag (varargin) |
|
30 |
|
31 if (nargin < 1) |
|
32 usage ("blkdiag (a, b, c, ...)"); |
|
33 endif |
|
34 |
|
35 if (! all (cell2mat (cellfun (@isnumeric, varargin)))) |
5552
|
36 error ("blkdiag: all arguments must be numeric"); |
5551
|
37 endif |
|
38 |
5552
|
39 ## Note: trailing singletons are automatically (correctly) ignored. |
5569
|
40 if (! all (cellfun ("ndims", varargin) == 2)) |
5551
|
41 error ("all of the arguments to blkdiag must be two-dimensional matrices"); |
|
42 endif |
|
43 |
5552
|
44 ## size is an option for cellfun, but it's a bit different from |
|
45 ## calling size directly. |
5551
|
46 csz = cumsum ([0 0; (cell2mat (cellfun (@size, varargin')))], 1); |
|
47 retval = zeros (csz(end,:)); |
5592
|
48 |
|
49 for p = 1:nargin |
5551
|
50 retval((csz(p,1)+1):csz(p+1,1),(csz(p,2)+1):csz(p+1,2)) = varargin{p}; |
|
51 endfor |
|
52 |
|
53 endfunction |
|
54 |
|
55 # regular tests |
|
56 %!assert(blkdiag(1,ones(2),1),[1,0,0,0;0,1,1,0;0,1,1,0;0,0,0,1]) |
|
57 %!assert(blkdiag([1,2],[3,4],[5,6]),[1,2,0,0,0,0;0,0,3,4,0,0;0,0,0,0,5,6]) |
|
58 %!assert(blkdiag([1,2],[3;4],[5,6]),[1,2,0,0,0;0,0,3,0,0;0,0,4,0,0;0,0,0,5,6]) |
|
59 %!assert(blkdiag([1,2;3,4],[5,6,7]),[1,2,0,0,0;3,4,0,0,0;0,0,5,6,7]) |
|
60 # tests involving empty matrices |
|
61 %!assert(blkdiag([],[],[]),[]) |
|
62 %!assert(blkdiag([],[1,2;3,4],[],5,[]),[1,2,0;3,4,0;0,0,5]) |
|
63 %!assert(blkdiag(zeros(1,0,1),[1,2,3],1,0,5,zeros(0,1,1)),[1,2,3,0,0,0;0,0,0,1,0,0;0,0,0,0,0,0;0,0,0,0,0,5]); |
|
64 # sanity checks |
|
65 %!test |
|
66 %! A = rand (round (rand (1, 2) * 10)); |
|
67 %! assert (blkdiag (A), A); |