-
Notifications
You must be signed in to change notification settings - Fork 0
/
aschar.m
85 lines (75 loc) · 1.78 KB
/
aschar.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
function str = aschar(obj)
%% aschar
% Author: Erik Roberts, 2018
%
% Purpose: give string representation of input suitable for using eval on
%
% TODO
% > 2d cell
% > 2d mat
% > 1 el logical
% struct array
if isempty(obj)
if isnumeric(obj)
str = '[]';
elseif iscell(obj)
str = '{}';
elseif ischar(obj)
str = 'aschar()';
end
elseif isstruct(obj) && isempty( fieldnames(obj) )
str = 'struct()';
elseif ischar(obj) && (sum( size(obj) ~= 1 ) <= 1)
str = ['''' obj ''''];
elseif isstring(obj)
str = ['"' char(obj) '"'];
elseif isnumeric(obj) && isscalar(obj)
str = num2str(obj);
elseif isnumeric(obj) && ~isscalar(obj) && ndims(obj) <= 2
str = num2str(obj);
str(:, end+1) = ';';
str(:, end+1) = ' ';
% cat rows
nRows = size(obj, 1);
temp = str;
str = '[';
for i = 1:nRows
str = [str temp(i, :)];
end
str(end-1:end) = []; % remove trailing '; '
str = [str ']'];
str = regexprep(str, '(\d)\s+', '$1, '); % replace whitespace with comma space
elseif islogical(obj) && isscalar(obj)
if obj
str = 'true;';
else
str = 'false';
end
elseif isa(obj, 'function_handle')
str = ['@' func2str(obj)];
elseif iscell(obj) && ndims(obj) <= 2
nRows = size(obj, 1);
nCols = size(obj, 2);
str = '{';
for i = 1:nRows
for j = 1:nCols
str = [str aschar(obj{i,j}) ', '];
end
str(end-1:end) = []; % remove trailing ', '
str = [str '; '];
end
str(end-1:end) = []; % remove trailing '; '
str = [str '}'];
elseif isstruct(obj) && all( size(obj) == 1 )
str = 'struct(';
flds = fieldnames(obj);
for iFld = 1:length(flds)
fld = flds{iFld};
str = [str '''' fld ''',' aschar(obj.(fld)) ', '];
end
str(end-1:end) = []; % remove trailing ', '
str = [str ')'];
else
error('Unsupported datatype');
end
end