1function df = struct2df(x, varargin)
2
3  %# function df = struct2df(x, varargin)
4  %# This function converts an ordinary structure into a dataframe.
5  %# Fieldnames are taken as columns names
6
7  %% Copyright (C) 2009-2017 Pascal Dupuis <cdemills@gmail.com>
8  %%
9  %% This file is part of the dataframe package for Octave.
10  %%
11  %% This package is free software; you can redistribute it and/or
12  %% modify it under the terms of the GNU General Public
13  %% License as published by the Free Software Foundation;
14  %% either version 2, or (at your option) any later version.
15  %%
16  %% This package is distributed in the hope that it will be useful,
17  %% but WITHOUT ANY WARRANTY; without even the implied
18  %% warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
19  %% PURPOSE.  See the GNU General Public License for more
20  %% details.
21  %%
22  %% You should have received a copy of the GNU General Public
23  %% License along with this package; see the file COPYING.  If not,
24  %% see <http://www.gnu.org/licenses/>.
25
26  names = fieldnames (x);
27  if (isscalar (x))
28
29    rowcount = structfun (@(x) size(x, 1), x);
30    df = cell(1+max (rowcount), length (names));
31    df(1, :) = names;
32
33    for indi = (length (names) : -1 : 1)
34      if (isa (x.(names{indi}), 'cell'))
35        df(1+(1:rowcount(indi)), indi) = x.(names{indi});
36      else
37        dummy = mat2cell (x.(names{indi}), repmat (1, [rowcount(indi) 1], 1));
38        df(1+(1:rowcount(indi)), indi) = dummy;
39      endif
40    endfor
41
42  else
43
44    rowcount = size (x, 1);
45    df = cell (1 + rowcount, length (names));
46    df(1, :) = names;
47
48    for indi = (length (names) : -1 : 1)
49      for indj = (1:rowcount)
50        df(1+indj, indi) = x(indj).(names{indi});
51      endfor
52    endfor
53  endif
54
55  df = dataframe (df);
56
57end
58