function gsave(varname, header);
%
% "gsave" stays for Giuliano's save MatLab function
% varname: MatLab varname of type CELL to be saved
% header: [facultative] a one row header of text for column headers
% ____________________________________________________________________
% EXAMPLES:
% gsave(Horizon2) --> Horizon2 is a cell array with header.
% gsave(mat) --> mat is a double array.
% gsave(mat, h_mat) --> mat is a double array and h_mat is its header.
% ____________________________________________________________________
% File name and path:
[FileName, PathName] = uiputfile({'*.txt','Text file [tab delimited] (*.txt)'; '*.xls','Excel (*.xls)'; '*.*','All Files (*.*)'}, 'Save File with(out) header', pwd);
% OPEN file
fid = fopen(strcat(PathName, FileName),'w');
% ----------- FORMATS -----------
H = 'n';
if nargin == 1
nformat1 = row_format(varname, 1); %-header format
nformat2 = row_format(varname, 2); %-corpus format
elseif nargin > 1 %if header exists
nformat1 = row_format(header, 1); %-header format
nformat2 = row_format(varname, 1); %-corpus format
end
% ----------- HEADER -----------
if nargin == 1
fprintf(fid, nformat1, varname{1,:});
else
fprintf(fid, nformat1, header{:});
end
% --------- CORPUS ----------
if nargin == 1, rStart = 2; else, rStart = 1; end
% start loop
for riga = rStart:size(varname,1)
fprintf(fid, nformat2, varname{riga,:} );
end
fclose(fid);
fclose('all');
disp('DONE!!');
%% prepare format
function nformat = row_format(v, row)
% This function takes 'v' variable at row number equal to 'row' and build the sequence of format string
% 'nformat', necessary for print to file.
if isa(v{row,1},'char'), nformat = '%s\t'; elseif isa(v{row,1},'numeric'), nformat = '%f\t'; end
for i = 2:size(v,2)
if isa(v{row,i},'char')
currFormat = '%s\t';
elseif isa(v{row,i},'numeric')
currFormat = '%f\t';
else
currFormat = '%s\t';
end
if i == size(v,2)
nformat = strcat(nformat, currFormat, '\n');
else
nformat = strcat(nformat, currFormat);
end
end