forked from BIMIB-DISCo/scFBA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconvertTable_Cell.m
97 lines (81 loc) · 2.1 KB
/
convertTable_Cell.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
function [DataOut] = convertTable_Cell(DataIn, header)
% Convert cell to table and vice versa, keeping the header and the first
% column with row labels
%
% USAGE:
%
% [varOut] = convertTable_Cell(varIn, header)
%
% INPUT:
% DataIn: MATLAB table or cell array.
%
% OPTIONAL INPUTS:
% header: TRUE if first row contain column labels in cell array
% or if want to keep variable names if a table is passed.
% FALSE if no header needed. (Default = TRUE)
%
% OUTPUTS:
% DataOut: cell arrays or MATLAB table converted.
%
%
% .. Author:
% - Davide Maspero 30/01/2018
if nargin < 2
header = true;
end
if istable(DataIn)
DataOut = NumTable2CellMatrix(DataIn, header);
elseif isnumeric(DataIn)
DataIn = num2cell(DataIn);
DataOut = CellMatrix2NumTable(DataIn, false);
elseif iscell(DataIn)
DataOut = CellMatrix2NumTable(DataIn, header);
else
warning('Conversion not allowed')
return
end
end
function [cellMatrixOut] = NumTable2CellMatrix(tableIn, header)
[r, c] = size(tableIn);
cellMatrixOut = cell(r,c);
for i=1:c
if isnumeric(tableIn.(i))
cellMatrixOut(:,i) = num2cell(tableIn.(i));
else
cellMatrixOut(:,i) = tableIn.(i);
end
end
if header
cellMatrixOut = [tableIn.Properties.VariableNames; cellMatrixOut];
end
end
function [tableOut] = CellMatrix2NumTable(CellMatrixIn, header)
[~, c] = size(CellMatrixIn);
tableOut = table();
if header
try
varName = cellstr(CellMatrixIn(1,:));
catch
error('No header found')
return
end
CellMatrixIn(1,:) = []; % prima riga rimossa
end
for i=1:c
try
ri = cellstr(CellMatrixIn(:,i));
catch
try
ri = cell2mat(CellMatrixIn(:,i));
catch
warning(char(strcat({'conversion error: column '}, num2str(i), {'type not allowed'})));
end
end
if exist('ri', 'var')
tableOut.(i) = ri;
end
end
if header
tableOut.Properties.VariableNames = varName;
end
end