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