5580
|
1 ## Copyright (C) 2005 Laurent Mazet |
|
2 ## |
7016
|
3 ## This file is part of Octave. |
5580
|
4 ## |
7016
|
5 ## Octave is free software; you can redistribute it and/or modify it |
|
6 ## under the terms of the GNU General Public License as published by |
|
7 ## the Free Software Foundation; either version 3 of the License, or (at |
|
8 ## your option) any later version. |
|
9 ## |
|
10 ## Octave is distributed in the hope that it will be useful, but |
|
11 ## WITHOUT ANY WARRANTY; without even the implied warranty of |
|
12 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
|
13 ## General Public License for more details. |
5580
|
14 ## |
|
15 ## You should have received a copy of the GNU General Public License |
7016
|
16 ## along with Octave; see the file COPYING. If not, see |
|
17 ## <http://www.gnu.org/licenses/>. |
5580
|
18 |
|
19 ## -*- texinfo -*- |
|
20 ## @deftypefn {Function File} {@var{m} =} cell2mat (@var{c}) |
|
21 ## Convert the cell array @var{c} into a matrix by concatenating all |
|
22 ## elements of @var{c} into a hyperrectangle. Elements of @var{c} must |
|
23 ## be numeric, logical or char, and @code{cat} must be able to |
|
24 ## concatenate them together. |
5642
|
25 ## @seealso{mat2cell, num2cell} |
5580
|
26 ## @end deftypefn |
|
27 |
|
28 function m = cell2mat (c) |
|
29 |
|
30 if (nargin != 1) |
6046
|
31 print_usage (); |
5580
|
32 endif |
|
33 |
|
34 if (! iscell (c)) |
|
35 error ("cell2mat: c is not a cell array"); |
|
36 endif |
|
37 |
|
38 nb = numel (c); |
|
39 |
|
40 if (nb == 0) |
|
41 m = []; |
|
42 elseif (nb == 1) |
|
43 elt = c{1}; |
|
44 if (isnumeric (elt) || ischar (elt) || islogical (elt)) |
|
45 m = elt; |
|
46 elseif (iscell (elt)) |
|
47 m = cell2mat (elt); |
|
48 else |
|
49 error ("cell2mat: all elements of cell array must be numeric, logical or char"); |
|
50 endif |
|
51 else |
|
52 ## n dimensions case |
|
53 for k = ndims (c):-1:2, |
|
54 sz = size (c); |
|
55 sz(end) = 1; |
|
56 c1 = cell (sz); |
|
57 for i = 1:(prod (sz)) |
|
58 c1{i} = cat (k, c{i:(prod (sz)):end}); |
|
59 endfor |
|
60 c = c1; |
|
61 endfor |
|
62 m = cat (1, c1{:}); |
|
63 endif |
|
64 |
|
65 endfunction |
|
66 |
|
67 ## Tests |
|
68 %!shared C, D, E, F |
|
69 %! C = {[1], [2 3 4]; [5; 9], [6 7 8; 10 11 12]}; |
|
70 %! D = C; D(:,:,2) = C; |
|
71 %! E = [1 2 3 4; 5 6 7 8; 9 10 11 12]; |
|
72 %! F = E; F(:,:,2) = E; |
|
73 %!assert (cell2mat (C), E); |
5716
|
74 %!assert (cell2mat (D), F); |
5580
|
75 ## Demos |
|
76 %!demo |
|
77 %! C = {[1], [2 3 4]; [5; 9], [6 7 8; 10 11 12]}; |
|
78 %! cell2mat (C) |