function str = cell2str(C)
% function str = cell2str(C)
% Convert cell structure to string such that eval(str) generates C.

% F. Felici SPC 2018

assert(iscell(C),'C must be a cell');
assert(ndims(C)<=2,'Cell arrays with more than 2 dimensions are not supported');

[nrow,ncol] = size(C);

str = '{';
for ii=1:nrow
  for jj=1:ncol
    celldata = C{ii,jj};
    if isstruct(celldata)
      error('structure inside cell not supported')
    elseif iscell(celldata)
      datastr = cell2str(celldata); % recursive call
    else
      datastr = field2str(celldata);
    end
    str = [str,datastr];
    if jj == ncol
      str = [str,';'];
    else
      str = [str,','];
    end
  end
end
str = [str,'}'];

end

function datastr = field2str(data)

if isnumeric(data) || islogical(data)
  datastr = mat2str(data,20,'class');
elseif ischar(data)
  datastr = ['''',data,''''];
else
  error('%s datatype not supported',class(data))
end
end