Monday, September 1, 2008

[Matlab] Saving 2D data in ASCII with matlab

function SaveDataAscii(data,filename,FileHead,Gformat)
% to save a 2d array into a ascii file as what you see in array editor
%     a format option is also provided
% Usage:
%     SaveDataAscii(data,filename,FileHead,Gformat)
% e.g.,
%       my2ddata=rand(3,5);
%       SaveDataAscii(my2ddata,'myrand2dtest.dat','it is a test','%7.4f');


isHeader=1;
if nargin==3
   Gformat='%10.4f';
elseif nargin==2
   isHeader=0;
   Gformat='%10.4f';
elseif nargin~=4
   help SaveDataAscii
   return
end
if (length(FileHead)==0)
   isHeader=0;
end

% open the file
fid=fopen(filename,'w');
if isHeader==1
   fprintf(fid,['%% ',FileHead]);
   fprintf(fid,'\n');
end

% write the datablock
for i=1:size(data,1)
    for j=1:size(data,2)
        fprintf(fid,Gformat,data(i,j));
    end;
    fprintf(fid,'\n');
end;
fclose(fid);

No comments:

ShowCalendar