5580
|
1 ## Copyright (C) 2005 Laurent Mazet |
|
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} {@var{m} =} cell2mat (@var{c}) |
|
19 ## Convert the cell array @var{c} into a matrix by concatenating all |
|
20 ## elements of @var{c} into a hyperrectangle. Elements of @var{c} must |
|
21 ## be numeric, logical or char, and @code{cat} must be able to |
|
22 ## concatenate them together. |
5642
|
23 ## @seealso{mat2cell, num2cell} |
5580
|
24 ## @end deftypefn |
|
25 |
|
26 function m = cell2mat (c) |
|
27 |
|
28 if (nargin != 1) |
|
29 usage ("m = cell2mat (c)"); |
|
30 endif |
|
31 |
|
32 if (! iscell (c)) |
|
33 error ("cell2mat: c is not a cell array"); |
|
34 endif |
|
35 |
|
36 nb = numel (c); |
|
37 |
|
38 if (nb == 0) |
|
39 m = []; |
|
40 elseif (nb == 1) |
|
41 elt = c{1}; |
|
42 if (isnumeric (elt) || ischar (elt) || islogical (elt)) |
|
43 m = elt; |
|
44 elseif (iscell (elt)) |
|
45 m = cell2mat (elt); |
|
46 else |
|
47 error ("cell2mat: all elements of cell array must be numeric, logical or char"); |
|
48 endif |
|
49 else |
|
50 ## n dimensions case |
|
51 for k = ndims (c):-1:2, |
|
52 sz = size (c); |
|
53 sz(end) = 1; |
|
54 c1 = cell (sz); |
|
55 for i = 1:(prod (sz)) |
|
56 c1{i} = cat (k, c{i:(prod (sz)):end}); |
|
57 endfor |
|
58 c = c1; |
|
59 endfor |
|
60 m = cat (1, c1{:}); |
|
61 endif |
|
62 |
|
63 endfunction |
|
64 |
|
65 ## Tests |
|
66 %!shared C, D, E, F |
|
67 %! C = {[1], [2 3 4]; [5; 9], [6 7 8; 10 11 12]}; |
|
68 %! D = C; D(:,:,2) = C; |
|
69 %! E = [1 2 3 4; 5 6 7 8; 9 10 11 12]; |
|
70 %! F = E; F(:,:,2) = E; |
|
71 %!assert (cell2mat (C), E); |
5716
|
72 %!assert (cell2mat (D), F); |
5580
|
73 ## Demos |
|
74 %!demo |
|
75 %! C = {[1], [2 3 4]; [5; 9], [6 7 8; 10 11 12]}; |
|
76 %! cell2mat (C) |